我正在使用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
) {
}
}
现在 appOS
和 formerName
属性可能是 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 回答
在我看来,没有必要把类型放在来自http响应的东西上......类型只存在于编译时,而不是在运行时......
代替:
用这个:
在这里,您将
data
声明为Response
类型在这里,您从
Response
类型的变量分配到UserStatus
类型的变量因此错误 .
要避免这样做