我已经检查过某些问题,但仍然无法解决我的问题。我在我的应用程序中使用了一个返回observables的服务,在这个阶段一切都很好,但是当我想显示数据时,没有任何反应:
@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>
...
可能是什么问题?
答案 0 :(得分:1)
使用箭头功能。没有它们,this
不会绑定到你的calback函数中的组件实例:
.subscribe(response => {
console.log("Success Response" + response);
this.events = response;
},
...