I have an angular service which returns the user object. The user object has its own attributes plus an array of walls. The service returns an observable to the calling component. In the service, I am able create a user object from the json returned by the http service. However, when I subscribe to the service in my component, the object returned is null. What am I doing wrong here?
// user.ts
import { wall } from './wall';
export class user {
Id: number;
EntryType: number;
UserType: number;
SubscriptionType: number;
IsCoach: boolean;
Username: string;
Email: string;
Name: string;
Password: string;
Created: string;
MemberWalls: wall[];
}
//wall.ts
export class wall {
Title: string;
ViewItem_Id: number;
}
//authentication.service.ts
authenticate(authRequest: login): Observable<user> {
let url: string = this.apiUrl + AppSettings.LOGIN_SERVICE;
let headers = new Headers({
'Content-Type': AppSettings.CONTENT_TYPE_HEADER, //'; charset=utf-8',
'client-secret': AppSettings.CLIENT_SECRET,
'client-id': AppSettings.CLIENT_ID
});
let options = new RequestOptions({ headers: headers });
return this._http.post(url, authRequest, options) //
.map(data => {
this.authenticated(data);
})
.catch(this.handleError);
}
private authenticated(res: Response) {
let body = res.json();
if (body.StatusCode === 200) {
localStorage.setItem('auth_token', res.headers.get("access-token"));
let user1: user = body.Data;
//The user object is fine here.
//That means that the json and the user class structure match perfectly
console.log(user1);
return body.Data || {};
}
else {
return {};
}
}
//login.component.ts
login() {
this.errorMessage = '';
this.currentUser = null;
this._authService.authenticate(this.loginModel)
.subscribe(user1 => this.currentUser = user1,
error => this.handleError( error));
//The user1 returned by the service is always null.
}
user1 => this.currentUser = user1,
is a function that is called when the data arrives. Code at the place where you have your comment is executed loooong before that. – Günter Zöchbauer