Reputation: 177
What is the proper method to assign a local object from an http response observable?
I want to assign myUser object to the response that I get from http, which is of the same type. Here is my code:
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { UpdateUser } from '../_models/updateuser';
@Injectable()
export class FormService {
private myUser : UpdateUser;
constructor(private http: Http) {
}
getUser(id: number): Observable<UpdateUser> {
const _url = 'https://192.168.1.2:4444/api/auth/getuser/' + id;
const headers = new Headers();
headers.append('X-User', sessionStorage.getItem('username'));
headers.append('X-Token', sessionStorage.getItem('token'));
headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({ headers: headers });
return this.http.get(_url, options)
.map(response => {
const responseAsObject = response.json();
this.myUser = responseAsObject; //<--- Here
console.log(this.myUser);
return responseAsObject;
});
}
logUser(){
console.log(this.myUser) //<--- undefined if called formService.logUser() from child components.
}
}
Logging this.myUser within the observable nets a positive result, however when I try to access the local variable from a child component that is provided by this service, it returns undefined, such as this.formService.logUser(); if used in a child component, returns undefined.
What is the proper method to broadcast an object from a service to a child component? I may be having async issues as the child component is being initialized before the service even gets the object from the http.
UPDATED QUESTION: Child Component
import { FormService } from '../../../../_services/form.service';
import { UpdateUser } from '../_models/updateuser';
@Component({
selector: 'update-form',
templateUrl: './updateForm.html',
providers: [FormService],
})
export class UpdateFormComponent implements OnInit{
private localUser : UpdateUser;
ngOnDestroy() {
}
constructor(
private formService: FormService,
) {}
ngOnInit() {
this.formService.logUser(); //undefined
this.formService.myUser = this.localUser; //Assign something like this, but with an observable..
}
}
So my end game is only to get the service to broadcast myUser for the child component to receive it and then display its data members to a form. But any time I assigned myUser to localUser it appears as undefined.
Upvotes: 3
Views: 3930
Reputation: 2454
You can try to use a BehaviorSubject to store the user object:
In your service:
private myUser = new BehaviorSubject<UpdateUser>(null);
getUser() {
// ...
return this.http.get(_url, options)
.map(response => {
const responseAsObject = response.json();
this.myUser.next(responseAsObject); // change the value!
console.log(this.myUser);
return responseAsObject;
});
}
logUser() {
console.log(this.myUser.getValue());
}
In your component:
export class UpdateFormComponent implements OnInit{
private localUser : UpdateUser;
constructor(
private formService: FormService,
) {}
ngOnInit() {
this.formService.myUser
.filter(user => user !== null)
.subscribe(user => {
this.formService.logUser(); // also 'user' here is the user object from the service, you can do whatever you want with it
});
}
}
Also, very important: you want the components to use the same instance of the service, so remove it from the providers from both components and add it to the providers of some higher level component, so that they share one instance.
Upvotes: 2