【问题标题】:Property 'includes' is missing in type 'Subscription' -angular2类型“订阅”-angular2 中缺少属性“包含”
【发布时间】:2017-08-20 13:37:50
【问题描述】:

我一直在尝试从节点获取对象数组到服务 onInit 并将其分配给组件。我可以查看服务中的数据,但是当我尝试分配给组件中的变量时,出现以下错误。我也包含了我的代码。请支持这一点。我只需要从服务中获取该数组并将其分配给组件中的决赛名单。

ERROR in 

    C:/Users/girija/Documents/animapp/src/app/components/list.component.ts (28,5): Type 'Subscription' is not assignable to type 'any[]'.
      Property 'includes' is missing in type 'Subscription'.

我的代码如下: app.service.ts:

   public finallist=[]
     getList(){
          return this.http.get('/api/list').subscribe(data=>{
             this.finallist=JSON.parse(data['_body']);
             return this.finallist;
        })
        }

app.component.ts:

  totallist=[];
     ngOnInit() {
        this.totallist=this.someService.getList();

      }

【问题讨论】:

    标签: javascript angular angular2-services angular-http


    【解决方案1】:

    subscribe 返回 Subscription 对象,这不是你要找的。​​p>

    试试这样的:

    app.service.ts

    getList(): Observable<any> {
      return this.http.get('/api/list').map(data => data['_body']);
    }
    

    app.component.ts

    totallist=[];
    
    ngOnInit() {
      this.someService.getList().subscribe(data => this.totallist = data);
    }
    

    【讨论】:

      【解决方案2】:

      您应该使用 map 运算符将响应转换为 json 类型

      getList(){
                return this.http.get('/api/list')
                   .map(response=> <Type>response.json()) /////////
                   .subscribe(data=>{
                   this.finallist=JSON.parse(data['_body']);
                   return this.finallist;
              })
              }
      

      注意:&lt;Type&gt; 用于严格输入

      【讨论】:

        【解决方案3】:

        请参阅下面的答案。它向您解释了如何从服务器获取数据,到服务,最后到组件。 Receiving Jason instead of html。我正在使用 mongodB,但您的后端可能不同。希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2020-02-05
          • 2019-04-28
          • 2022-01-03
          • 1970-01-01
          • 2019-06-02
          • 2021-06-24
          • 2020-01-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多