Angular2和TypeScript:错误TS2322:类型"Response"不能分配给类型"UserStatus" [英] Angular2 and TypeScript: error TS2322: Type 'Response' is not assignable to type 'UserStatus'

查看:804
本文介绍了Angular2和TypeScript:错误TS2322:类型"Response"不能分配给类型"UserStatus"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2和TypeScript,但运行不顺利(在AngularJS中这很容易).我正在写一个小实验应用程序来掌握所有内容,我将以下组件作为主要/顶级组件...

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 I have the following component as my main / top level component...

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'):

Now when the top level component is bootstrapped / initialised I want to make a call to a phoney REST service (/restservice/userstatus) I set up that returns an object that I have made into a type like so (this is from 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对象,如下所示:

Now the appOS and formerName properties could potentially be null and when serving up the response in my REST service they are, the JSON object looks like so:

{
    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 Service的数据分配给类'this.userStatus = data;'中的组件时,从我的电话服务发送的数据结构和Type Object匹配,但是出现以下错误....

So the data structure sent from my phoney service and the Type Object match however when I try to assign the data from the Rest Service to component in the class 'this.userStatus = data;' I get the following error....

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

我假设在我的Type类中,与null有关的定义在做错事情,任何人都可以看到我在做错什么或解释为什么我得到了错误.预先感谢.

I assume in my Type class I am doing something wrong with the definition where nulls are concerned can anyone see what I am doing wrong or explain why I am getting the error. Thanks in advance.

推荐答案

在我看来,没有必要将类型放在来自HTTP响应的内容上.类型仅存在于编译时,而不存在于运行时中.

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

代替:

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

这篇关于Angular2和TypeScript:错误TS2322:类型"Response"不能分配给类型"UserStatus"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆