Property 'includes' is missing in type 'Subscription' -angular2

心不动则不痛 提交于 2019-12-23 03:34:14

问题


I have been trying to get an array of objects from node to a service onInit and assign it to component. I am able to view data in service but when i try to assign to a variable in component, I get below error. I have included my code as well. Please favour on this.All i need is to just take that array from service and assign it to finallist in component.

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'.

My code is below: 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();

      }

回答1:


subscribe returns Subscription object, this is not what you have looking for.

Try something like this:

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:


You should be using a map operator to convert the response into json type

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

Note : <Type> is used for strict typing




回答3:


See my answer below. It explains to you how to get your data from the server, to service, and finally to component. Receiving Jason instead of html. I am using mongodB but your backend may be different. Hope this helps.



来源:https://stackoverflow.com/questions/45782739/property-includes-is-missing-in-type-subscription-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!