【问题标题】:observable data not available in subscribe订阅中不可用的可观察数据
【发布时间】:2017-09-04 13:11:23
【问题描述】:

以下是我的 api 调用,中间有拦截器,所以我从本地存储中获取这些数据。数据被字符串化并保存。当我返回它时,我通过 observable.of(cachedata) 转换为 observable。

  getApplications(userid: string): Observable<any> {
    let data =this.httpclient.get(this._getAPIUrl('user/' + userid + '/applications'))
      .map((res: Response) => res.json())
      return data;
  }

我从组件中调用它

  ngOnInit() {
        const userid = this.platformService.currentUserId;
        console.log(this.platformService.getApplications(userid));
}

打印结果

Observable {_isScalar: false, source: Observable, operator: MapOperator}

如果我订阅此通话数据不可用。

 this.platformService.getApplications(userid)
  .subscribe(applications => {
            console.log('app ' + applications);
            const menuItems: MenuItem[] = [];
            menuItems.push(
                new MenuHeaderItem({
                    type: MenuItemType.Header,
                    title: 'Applications',
                    description: null
                }));
            Object.keys(applications).map(element => {
                menuItems.push(this.formatconversion(applications[element]));
            });
            this.menu = menuItems;
        });

console.log('app' + applications) 不来。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 您的代码似乎有效,因为一旦成功解决了 http get 调用,就应该调用 subscribe 块中的代码。您是否在控制台中遇到任何错误?

标签: angular angular2-services


【解决方案1】:

我认为您的代码有问题 而不是这个

getApplications(userid: string): Observable<any> {
let data =this.httpclient.get(this._getAPIUrl('user/' + userid + '/applications'))
  .map((res: Response) => res.json())
  return data;

}

使用这个

getApplications(userid: string): Observable<any> {
this.httpclient.get(this._getAPIUrl('user/' + userid + '/applications'))
  .map((res: Response) => res.json())

}

无需返回。

res.json()

将返回服务器响应的内容。试试这个,让我知道它是否有效:)

【讨论】:

  • 它不工作,错误属性 'subscribe' 在类型 'void' 上不存在
  • getApplications(userid: string) { this.httpclient.get(this._getAPIUrl('user/' + userid + '/applications')) .map((res: Response) => res. json())} 试试这个。对我来说它的工作。
  • 在我的情况下,我从本地存储中获取此对象,我正在保存 httpresponse 对象并将其检索回来,该对象保存在字符串中。所以这里的问题是 httpresponse 对象不能以字符串格式保存,如果我这样做,它不能解析回普通对象。我得到了无效的 json 来转换为 js 对象。这就是问题所在。
  • 是的,我们不能将 httpresponse 对象存储在字符串中,这就是为什么我们在服务器中使用 res.json() 将其发送到组件,在那里我们可以看到来自的对象类型服务器,因此可以存储该对象。
猜你喜欢
  • 2019-12-31
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
相关资源
最近更新 更多