Angular2 and TypeScript: error TS2322: Type 'Response' is not assignable to type 'UserStatus'

后端 未结 3 1164
北恋
北恋 2021-01-04 00:04

I\'m playing with Angular2 and TypeScript and it\'s not going well (this would be so easy in AngularJS). I\'m writing a little experiment app to get to grips with it all and

相关标签:
3条回答
  • 2021-01-04 00:42

    Here you declare data as type Response

    (data: Response) => { // <==
         data = JSON.parse(data['_body']);
    

    and here you assign from a variable of type Response to a variable of type UserStatus

          this.userStatus = data; 
    

    thus the error.

    To avoid that just do

    this.userStatus = JSON.parse(data['_body']);
    
    0 讨论(0)
  • 2021-01-04 00:46

    You can try

    (data: Response|any) => { // <==
     data = JSON.parse(data['_body']);
    

    Helped me out

    0 讨论(0)
  • 2021-01-04 00:53

    In my opinion there is no point to put type on something that comes from http response... Types exists only in compilation time, not in runtime...

    Instead of:

    this.http.get('/restservice/userstatus', {headers: headers})
            .subscribe(
            (data: Response) => {
                data = JSON.parse(data['_body']);
                this.userStatus = data;
            },
            err => console.log(err), // error
            () => console.log('getUserStatus Complete') // complete
        );
    

    Use this:

    this.http.get('/restservice/userstatus', {headers: headers})
    .map((data: any) => data.json())
    .subscribe(
            (data: any) => {
                this.userStatus = data;
            },
            err => console.log(err), // error
            () => console.log('getUserStatus Complete') // complete
        );
    
    0 讨论(0)
提交回复
热议问题