Something strange is happening with my code.
I am working with a JSON object:
{"login":"admin","name":"Admin"}
And this is the relevant part of my code:
private _userData: User;
...
private getUserData() {
this._userInfoService.getUserInfo()
.subscribe(
data => {
this._userData = data.json(); // (using <User> data.json() changes nothing
},
err => alert(err)
);
}
This is how I defined the User interface:
export interface User {
login: string;
name: string;
}
But when trying to display the data in HTML using Angular:
<p>{{ _userData.login }}</p>
<p>{{ _userData.name }}</p>
I encounter errors like:
Error: EXCEPTION: TypeError: l__userData21 is null in [{{ _userData.login }} in UserHomeComponent@8:7]
Even though console.log shows the correct object:
Object { login: "admin", name: "Admin" }
The strange thing is, when I slightly modify the code like this:
private _name: string;
private _login: string;
...
private getUserData() {
this._userInfoService.getUserInfo()
.subscribe(
data => {
this._name = (<User> data.json()).name;
this._login = (<User> data.json()).login;
},
err => alert(err)
);
}
and adjust the view accordingly:
<p>{{ _login }}</p>
<p>{{ _name }}</p>
Then everything works fine! I'm puzzled by this issue (tried casting to <User> but it didn't help.)
@Edit: I have another class where similar code works perfectly:
export interface LoginData {
access_token: string;
token_type: string;
refresh_token: string;
expires_in: number;
scope: string;
}
private _loginData = <LoginData> JSON.parse(sessionStorage.getItem("loginData")); //tried this also with User, doesn't work
and in the view:
<p>access_token: {{ _loginData.access_token }}</p>
<p>token_type: {{ _loginData.token_type }}</p>
<p>refresh_token: {{ _loginData.refresh_token }}</p>
<p>expires_in: {{ _loginData.expires_in }}</p>