サーバーからデータをロードする場合は、角度アプリにします。しかし、データ要求はasync
であり、データを正しく取得できません。最初に私はurlパラメータを渡します。パラメータに基づいて、私はngOnInit()
からデータをロードしますが、データが正しくロードされていません。私は時間を捜していますが、解決策はありません。私のコードは以下の通りである: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妊娠?前もって感謝します。
<div class="form-group">
<label for="exampleInputEmail1">Initial</label>
<!-- this code causes error -->
<p> {{author?.initial}} </p>
</div>
データが
ここで、あなたのケースでのように非同期に来ている場合には、有益なエラーをスローすることは、角防ぐことができます[もsafe navigation operator
呼ば] elevisオペレータ(?)
を使用することにより:
があなたのhtmlコードを投稿し、データがそれをバインドする利用可能な場合、それはエラーをスローするように、角度防ぐことができますチェックする
safe operator
を使用することができます – Sajeetharan