“Type 'Object' is not assignable to type” with new HttpClient / HttpGetModule

后端 未结 2 796
我寻月下人不归
我寻月下人不归 2020-12-03 10:52

Following Google\'s official Angular 4.3.2 doc here, I was able to do a simple get request from a local json file. I wanted to practice hitting a real endpoint

2条回答
  •  鱼传尺愫
    2020-12-03 11:43

    You actually have a few options here, but use generics to cast it to the type you're expecting.

       // Notice the Generic of IUsers[] casting the Type for resulting "data"
       this.http.get(this.productUrl).subscribe(data => ...
    
       // or in the subscribe
       .subscribe((data: IUsers[]) => ...
    

    Also I'd recommend using async pipes in your template that auto subscribe / unsubscribe, especially if you don't need any fancy logic, and you're just mapping the value.

    users: Observable; // different type now
    
    this.users = this.http.get(this.productUrl);
    
    // template:
    *ngFor="let user of users | async"
    

提交回复
热议问题