angular2服务 - RXjs

时间:2016-12-07 13:38:16

标签: angular rxjs

如何在trynig按ID获取项目时如何防止错误 - 如果我刷新页面 - 这是代码:

服务代码:

 getServices(): Observable <any> {
        return this._http.get(this.APIURL + 'serives.json')
            .map((resposne: Response) => <any> resposne.json())
            .do(data => {
                this.services = data
            })
            .catch(this.hendelError)
    }

getService(id): any {
    let myService;
    if (this.services.length) {
        myService = this.services.filter(service => service.id === id);
        return myService;
    } else {
        this.getServices().subscribe(
            data => {
                myService = this.services.filter(service => service.id === id);
                return myService;
            }
        )
    }

}

private hendelError(error: Response) {
    console.log('error', error);
    return Observable.throw(error.json().error || 'server error');
}

,组件代码为:

 ngOnInit() {
    if(this._manager.services.length){
      this.services = this._manager.services;
      return;
    }else{
      this._manager.getServices()
          .subscribe(
              data => {this.services = data;
                console.log('data',data);}
          )
    }
  }

当我刷新页面时,我收到此错误:

main.bundle.js:46117 EXCEPTION: Uncaught (in promise): Error: Error in ./ServicedetailsComponent class ServicedetailsComponent_Host - inline template:0:0 caused by: Cannot read property '0' of undefi定义

1 个答案:

答案 0 :(得分:0)

Angular 2不是“刷新页面”友好。刷新页面时,您将重新加载应用程序。

解决方案是传递路径中的所有上下文(使用路由器)和sessionStorage(或localStorage)。然后,您将能够在当前上下文中重新加载应用程序。