我的angular2 app使用ngfor指令显示json数组中的数据。以前我将json数组硬编码到组件中以进行测试,应用程序运行良好。现在我已经为使用http请求提供json数组的服务切换了硬编码的json数组。我可以点击几次提供此数据的链接(在2-4次之间变化),并且它工作正常,然后它会抛出错误
这是app.routes.ts
...
{path:'deals', component:Deals},
...
路由器链接
<li id="deals" (click)="loadField('deals')"><a [routerLink]="['/deals']"><p class="propertyNavItem" id="dealsText">Deals</p></a></li>
交易组件
dev_file:string = "dev_files/deals.json";
list:Array<string>;
constructor(private ghttp: GeneralHttpService){}
ngOnInit(){
this.ghttp.getRecommendations(this.dev_file).subscribe(
data=>{
this.list = data.items;
},
error => console.log(error),
() => console.log("done")
);
}
ghttp服务
@Injectable()
export class GeneralHttpService{
constructor(private http:Http){};
getRecommendations(url:string){
return this.http.get(url).map(res => res.json() );
}
}
抛出的错误就是这个。它看起来与问题https://github.com/angular/angular/issues/9479
相同EXCEPTION: Error: Uncaught (in promise): Error: Outlet is not activated browser_adapter.js:86 EXCEPTION: Error: Uncaught (in promise): Error: Outlet is not activated browser_adapter.js:77:13 STACKTRACE: browser_adapter.js:77:13 resolvePromise@http://localhost:4200/vendor/zone.js/dist/zone.js:538:32 makeResolver/<@http://localhost:4200/vendor/zone.js/dist/zone.js:515:14 Zone</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:4200/vendor/zone.js/dist/zone.js:323:20 NgZoneImpl/this.inner<.onInvoke@http://localhost:4200/vendor/@angular/core/src/zone/ng_zone_impl.js:45:32 Zone</ZoneDelegate</ZoneDelegate.prototype.invoke@http://localhost:4200/vendor/zone.js/dist/zone.js:322:20 Zone</Zone</Zone.prototype.run@http://localhost:4200/vendor/zone.js/dist/zone.js:216:25 scheduleResolveOrReject/<@http://localhost:4200/vendor/zone.js/dist/zone.js:571:53 Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:4200/vendor/zone.js/dist/zone.js:356:24 NgZoneImpl/this.inner<.onInvokeTask@http://localhost:4200/vendor/@angular/core/src/zone/ng_zone_impl.js:36:32 Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask@http://localhost:4200/vendor/zone.js/dist/zone.js:355:24 Zone</Zone</Zone.prototype.runTask@http://localhost:4200/vendor/zone.js/dist/zone.js:256:29 drainMicroTaskQueue@http://localhost:4200/vendor/zone.js/dist/zone.js:474:26 ZoneTask/this.invoke@http://localhost:4200/vendor/zone.js/dist/zone.js:426:22 browser_adapter.js:77:13
答案 0 :(得分:0)
http是一种异步操作。在渲染模板时,您的列表变量可能尚未填充。
尝试在ngFor中使用“elvis operator”(?),如下所示:
*ngFor="let listElement of list?"