我想从我的Angular应用程序中的服务器加载数据。但数据请求是async
,我无法正确获取数据。首先我传递url参数。根据参数,我从ngOnInit()
加载数据,但数据未正确加载。我在Google上搜索时间,但没有解决方案。Angular2:从服务器加载的异步数据
服务
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Author} from './author';
@Injectable()
export class AuthorService {
private headers = new Headers({
'Content-Type': 'application/json'
});
private authorUrl = 'api/author';
constructor(private http:Http) { }
getAuthor(authorId : String):Promise<Author> {
return this.http.get(this.authorUrl + '/get/'+ authorId)
.toPromise()
.then(res => res.json().data as Author)
.catch(this.handleError)
}
}
组件
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AuthorService } from '../author/author.service';
import { Author } from '../author/author';
@Component({
selector: 'book-list',
templateUrl: './book.component.html'
})
export class BookComponent implements OnInit {
constructor(private route: ActivatedRoute, private authorService: AuthorService) { }
fetchAuthor(authorId): Promise<Author> {
return this.authorService.getAuthor(authorId)
}
ngOnInit() : void {
this.fetchAuthor(this.id).then((author) => {
this.author = author; // here value is avaliab
});
// here value is undefined
console.log('author data : ', this.author);
/*
// I also have tried this
this.authorService
.getAuthor(this.id)
.then(author => {
this.author = author;
console.log(this.author); // here value available
});
console.log(this.author); // here value is not available
*/
};
}
HTML
<div class="form-group">
<label for="exampleInputEmail1">Initial</label>
<!-- this code causes error -->
<p> {{author.initial}} </p>
</div>
任何SUG:我下面的代码给出GESTION?提前致谢。
发表您的html代码 – Sajeetharan