Currently, I am facing some challenges while working with Angular2 and TypeScript. Transitioning from AngularJS to Angular2 has proven to be a bit tricky for me. To better understand this new framework, I decided to create an experimental app with the following component as my main and 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',
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() {
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
);
}
}
In my application, when the top-level component is initialized, I want to make a call to a mock REST service (/restservice/userstatus) that returns an object structured like the UserStatus
type defined in my types file:
export class UserStatus {
constructor (
public appOS?: any ,
public firstName: string,
public formerName?: any,
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
) {
}
}
The properties appOS
and formerName
can be null in the response from my mock service, but when trying to assign this response to this.userStatus = data;
, I encounter the following error...
"error TS2322: Type 'Response' is not assignable to type 'UserStatus'.
Property 'appOS' is missing in type 'Response'."
It seems there might be an issue with how I have defined the type class, particularly regarding null values. Can anyone spot what I might be doing wrong or offer an explanation for this error? Appreciate any help provided. Thank you.