Angular7订阅服务器不是功能

时间:2019-08-22 17:38:40

标签: angular promise observable subscriber

//myService.ts
//customhttpservice is just an observable returning http request response.



public getCPData(): Observable<any> {

    if (localStorage.getItem('resind')) {
     return of(JSON.parse(localStorage.getItem('resind')));
    } else {

      return this.customHttpService.get(url, headers, params, '')
      .toPromise()
      .then(resp => {
        localStorage.setItem('resind', resp)
        return resp;
       },
       error => console.error(error)
      );
    }
   }

//myComponent.ts


this.myService.getCPData().subscribe(data => {
      console.log('data', data);
    });

对于以上代码,当我尝试订阅myservice时,我正在接收订户不是功能错误。有人可以帮我这里有什么问题吗。

1 个答案:

答案 0 :(得分:2)

您不能订阅诺言,而是返回一个可观察到的内容:

 import { tap, catchError } from 'rxjs/operators';

 // ...

 return this.customHttpService.get(url, headers, params, '').pipe(
   tap(resp => localStorage.setItem('resind', resp))
   catchError( /** do stuff **/)
 )