user2180794 user2180794 - 6 months ago 112
Node.js Question

Angular2 Passing parameters to web service http GET

I have a profileComponent which is making a GET call to service endpoint as follows , AparmentService is injected in bootstarp, hence no providers

@Component({
selector: 'profile',
template: `<h1>Profile Page</h1>

{{userEmail.email}}
{{profileObject | json}}
`,
directives: [ROUTER_DIRECTIVES]
})

export class ProfileComponent implements OnInit {
userEmail = JSON.parse(localStorage.getItem('profile'));
public profileObject: Object[];


constructor(private apartmentService: ApartmentService) {
this.apartmentService = apartmentService;
}

ngOnInit(): any {
console.log(this.userEmail.email); <--This value displays fine in the console
this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res); <-- getting [] response for this
console.log(JSON.stringify(this.profileObject)); <-- undefined
}
}


The service looks like this

@Injectable()
export class ApartmentService {

http: Http;
constructor(http: Http) {
this.http = http;
}

getProfile(userEmail :string){
return this.http.get('/api/apartments/getprofile/:userEmail').map((res: Response) => res.json());
}
}


when I try to hit the endpoint directly in the browser with the parameter, I am getting the respone. But not within Angular.

Any Ideas ?

Answer

http.get() is async

ngOnInit(): any {
    console.log(this.userEmail.email);                <--This value displays fine in the console 
    this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);  <-- getting [] response for this 
    // at this position the call to the server hasn't been made yet.
    console.log(JSON.stringify(this.profileObject));   <-- undefined         
}

When the response from the server arives res => this.profileObject = res is executed. console.log() is made before the call to the server was even initalized

Use instead

ngOnInit(): any {
    console.log(this.userEmail.email);                <--This value displays fine in the console 
    this.apartmentService.getProfile(this.userEmail.email)
    .subscribe(res => {
      this.profileObject = res; 
      console.log(JSON.stringify(this.profileObject));
    });
}

I think :userEmail in the URL isn't doing what you expect. Try instead:

getProfile(userEmail :string){
   return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
}