首页 文章

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

提问于
浏览
14

我正在使用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
}

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

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

我假设在我的Type类中我做错了定义,其中null可以让任何人看到我做错了或解释为什么我得到错误 . 提前致谢 .

2 回答

  • 5

    在我看来,没有必要把类型放在来自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
        );
    
  • 24

    在这里,您将 data 声明为 Response 类型

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

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

    this.userStatus = data;
    

    因此错误 .

    要避免这样做

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

相关问题