0

I have a function in an angular2 service, which is passed an id to append to a base URL for a Http get request however it doesn't work. When i put in the exact string it gets the data fine, but it won't let me append the variable like

'http://localhost:3000/project/allTask/' + project_id

getTasks(project_id){
  this.loadToken();
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.get('http://localhost:3000/project/allTask/5b0919ea256f2e15f8f4364f' , {headers: headers})
    .map(res => res.json());
}

Update:

I believe the project_id when passed in undefined. This is a function of my component.

ngOnInit() {

this.authService.getProfile().subscribe(profile => {
   this.user_id = profile.user._id;
   console.log(this.user_id); //RETURNS CORRECT ID HERE
},
err =>{
   console.log(err);
   return false;
});

console.log(this.user_id);//UNDEFINED

this.authService.getProjects(this.user_id).subscribe(data => {
   this.projects = data;
},
err =>{
   console.log(err);
   return false;
});
}
7
  • 1
    Are you sure project_id contains the correct string? Try to log it to the console to check. Commented May 29, 2018 at 6:51
  • Listen to @Henry, make a console log of your ID, because from what you say you tried, it should work. Commented May 29, 2018 at 6:55
  • It is undefined when it enters this function which is odd. Commented May 29, 2018 at 6:56
  • The log in the first lambda expression is executed after the second one. The user_id is only set after you receive an answer from the getProfile call. Read about asynchronous execution. Commented May 29, 2018 at 7:08
  • Thanks for your help Henry. Anyway to fix it in the mean time though? Commented May 29, 2018 at 7:12

1 Answer 1

2

Just use it like this:

getTasks(project_id){
  this.loadToken();
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.get('http://localhost:3000/project/allTask/' + project_id, {headers: headers})
    .map(res => res.json());
}

or

getTasks(project_id){
  this.loadToken();
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.get(`http://localhost:3000/project/allTask/${project_id}`, {headers: headers})
    .map(res => res.json());
}
Sign up to request clarification or add additional context in comments.

3 Comments

You're not using the correct operator for string templates.
@trichetriche is it fine now?
(But in your first example, it's trivial, you shouldn't have edited the first chunk of code. But since it works, that's just being picky)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.