0
我已經檢查了一些問題,但仍然無法解決我的問題。我用我的應用程序返回觀測服務,一切都在這個舞臺上很好,但是當我想顯示的數據,沒有任何反應:角2 * ngFor和觀察對象,沒有數據顯示
@Injectable()
export class DataService {
private APIURL = 'http://api.dev/';
constructor(private http: Http) {
}
_API_getEvents:string = this.APIURL + "getEvents";
getEvents() : Observable<IEvent[]> {
return this.http.get(this._API_getEvents)
.map((res:Response) => res.json())
.catch(this.handleError);
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
事件接口:
export interface IEvent {
id: number;
name: string;
created_at:Date;
update_at:Date;
}
而且成分:
events:IEvent[];
//events:any[];
constructor(private _http:Http, private _dataService: DataService)
{
this._dataService.getEvents()
.subscribe(
function(response) { console.log("Success Response" + response);
this.events = response;
console.log('EVENTS: ');
console.log(this.events);
},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
}
當我試圖顯示,其空:
<ul *ngIf="events">
<li *ngFor="let event of events">
<a [routerLink]="['/gallery/', 'event1']">
{{event.name}}
</a>
</li>
...
可能是什麼問題?
你可以把你的代碼放在plunkr中嗎?我幾乎找不到任何不起作用的東西。假設數據正在組件級別上進行安慰。 – Smit
到目前爲止,console.log顯示數據已成功獲取,但我有一種感覺,即在此之前呈現的視圖。但是當我搜索類似的話題時,人們通常會添加* ngIf指令並解決問題,但在我看來並不是這樣。我將嘗試創建plunkr – d123546
我還建議將您的代碼在您的構造函數中移動到ngOnInit。如果您最終開始在您的組件上使用Input綁定,它將無法按您期望的方式工作,因爲在調用構造函數時,Angular尚未初始化任何綁定。這只是一個很好的做法,儘量減少你在組件的構造函數中做的工作 – snorkpete