Angular2和TypeScript:错误TS2322:类型'响应'不能分配给' UserStatus'

时间:2016-02-04 15:19:58

标签: typescript angular

我正在玩Angular2和TypeScript并且它不顺利(这在AngularJS中会非常容易)。我正在编写一个小实验应用程序以掌握所有内容,并且我将以下组件作为我的主要/顶级组件......

import {Component, OnInit} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {UserData} from './services/user-data/UserData';
import {Home} from './components/home/home';
import {UserStatus} from './types/types.ts';
import {Http, Headers, Response} from 'angular2/http';

@Component({
    selector: 'app', // <app></app>
    providers: [...FORM_PROVIDERS],
    directives: [...ROUTER_DIRECTIVES],
    template: require('./app.html')
})
@RouteConfig([
    {path: '/', component: Home, name: 'Home'},
    // more routes here....
])

export class App {

    userStatus: UserStatus;

    constructor(public http: Http) {
    }

    ngOnInit() {

        // I want to obtain a user Profile as soon as the code is initialised
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        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
        );
    }    
}

现在,当顶层组件被引导/初始化时,我想调用一个虚假的REST服务(/ restservice / userstatus)我设置了一个返回我已经创建的类型的对象(这是来自import {UserStatus} from './types/types.ts'):

export class UserStatus {

    constructor (
        public appOS?: any , // can be null
        public firstName: string,
        public formerName?: any, // can be null
        public fullPersId: number,
        public goldUser: boolean,
        public hasProfileImage: boolean,
        public hideMoblieNavigationAndFooter: boolean,
        public persId: string,
        public profileName: string,
        public profilePicture: string,
        public showAds: boolean,
        public siteId:  number,
        public url: string,
        public verified: boolean
    ) {

    }
}

现在appOSformerName属性可能是null,当我在REST服务中提供响应时,JSON对象如下所示:

{
    appOS: null,
    firstName: "Max",
    formerName: null,
    fullPersId: 123456789,
    goldUser: true,
    hasProfileImage: true,
    hideMoblieNavigationAndFooter: false,
    persId: "4RUDIETMD",
    profileName: "Max Dietmountaindew",
    profilePicture: "http://myurl.com/images/maxdietmountaindew.jpg",
    showAds: true,
    siteId: 1,
    url: "/profile/maxdietmountaindew",
    verified: true
}

因此,当我尝试将Rest服务中的数据分配给类'this.userStatus = data;'中的组件时,从我的phoney服务和Type Object发送的数据结构匹配,我得到以下错误....

"error TS2322: Type 'Response' is not assignable to type 'UserStatus'.
  Property 'appOS' is missing in type 'Response'."

我假设在我的Type类中我正在做出错误的定义,其中涉及空值,任何人都可以看到我做错了或解释为什么我得到错误。提前谢谢。

3 个答案:

答案 0 :(得分:25)

在我看来,没有必要把类型放在来自http响应的东西上......类型只存在于编译时,而不是在运行时......

而不是:

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
    );

使用此:

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
    );

答案 1 :(得分:6)

在此,您将data声明为Response

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

在这里您从类型Response的变量分配到UserStatus类型的变量

      this.userStatus = data; 

因此错误。

要避免这样做

this.userStatus = JSON.parse(data['_body']);

答案 2 :(得分:1)

您可以尝试

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

帮助了我