我確定問題是關於異步,但找不到解決方案。我創建了一個獲取JSON數據數組的服務。在我的組件中,我想在頁面加載時顯示這些數據。 當頁面加載時,我沒有收到任何數據,但我創建了一個按鈕,並將onclick事件放在同一個函數中。我在點擊事件上獲取數據。我究竟做錯了什麼?無法在Angular 2的init上獲取Ajax數據
我的組件
import { Component } from '@angular/core';
import {PostService} from './post.service';
@Component({
selector: 'app-root',
template: `
{{test}}
<ul>
<li *ngFor="let item of jsonArray">
{{item.title}} a
</li>
</ul>
<button on-click="onClick()">button</button>
`
})
export class AppComponent {
test;
jsonArray : any[];
constructor(private _postService : PostService){
}
onClick(){
this.jsonArray = this._postService.getPosts();
this.test = "clicked";
}
ngOnInit(){
this.jsonArray = this._postService.getPosts();
this.test = "init";
}
}
和我的服務類
import {Http} from '@angular/http'
import 'rxjs/add/operator/map';
import {Injectable} from '@angular/core';
@Injectable()
export class PostService {
private _url = "https://jsonplaceholder.typicode.com/posts";
jsonArray: any[];
getPosts():any[]{
//return this._http.get(this._url).map(res =>res.json());
this._http.get(this._url).subscribe(response => {
this.jsonArray = response.json();
console.log(response.json());
console.log("jsonArray",this.jsonArray);
});
return this.jsonArray;
}
createPost(post){
return this._http.post(this._url,JSON.stringify(post)).map(res =>res.json());
}
constructor(private _http:Http){
}
}
https://stackoverflow.com/documentation/angular2/3577/angular-rxjs-subjects-and-observables閱讀提供的鏈接-with-api-requests/12348/basic-request#t = 20170726145040649751 – JGFMK
您是否收到任何錯誤。我是使用您的代碼的凝結結果。控制檯中是否有錯誤? –
沒有錯誤,我試圖看到頁面上的數據不在控制檯上。您是否看到網頁上的數據? @RajBahadurSingh – rematnarab