我想在 Angular app 中从服务器加载数据。但是数据请求是async
,我无法正确获取数据。首先我传递url参数。基于参数,我从ngOnInit()
加载数据,但数据未正确加载。我用谷歌搜索,但没有解决方案。我的代码如下:
服务
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>
有什么建议吗?在此先感谢。
答案 0 :(得分:0)
试试这个safe operator/elvis operator (?)
:
<div class="form-group">
<label for="exampleInputEmail1">Initial</label>
<!-- this code causes error -->
<p> {{author?.initial}} </p>
</div>
通过使用elevis运算符(?)
[也称为safe navigation operator
],它将阻止角度抛出错误,这有利于数据像您的情况一样异步传输
以下是有关此内容的详细信息
https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator
答案 1 :(得分:0)
您可以使用safe operator
检查数据是否可用然后绑定它,它会阻止角度抛出错误,
<label for="exampleInputEmail1">Initial</label>
<p> {{author?.initial}} </p>
</div>