0

I created a service in angular named UserService, and a function in app.componenet.ts that invites it. Here is the code in the UserServer:

//login function in the UserService – gets user's id and returns his name
Login(userId: string):Observable<string>
  {
    let headers=new Headers({'Content-type':'application/json;charset=utf-8'});
    return this.http.get<string>(`${this.url}/login/${userId}`);
  }

and this is the function in the app.componenet.ts:

 Login()
 {
  this.userService.Login(this.userID).subscribe(n=>{
    alert('your name is'+n)
  });
 }

The problem is that the Login function in the componenet doesn't enter the subscribe function. It enters the Login function in the Service but not to the subscribe. What should I do?

I followed the code with debugger and didnt see anything strange

8
  • Most probably you got an error response from http get. Besides that, it would work like you expect. Commented Mar 22, 2022 at 11:30
  • your headers are unused. Commented Mar 22, 2022 at 11:31
  • So how can I fix it? (the headers) Commented Mar 22, 2022 at 11:38
  • I don't know, you didnt even provide what is the console output How to Ask Commented Mar 22, 2022 at 11:40
  • 1
    Great, and dont you think that actual error content could explain what is wrong? You got http error like I wrote in before so it will not get into the next part of your subscriber method. Commented Mar 22, 2022 at 11:43

2 Answers 2

1
Login(userId):Observable<any>{
    return this.http.get(`${this.url}/login/${userId}`);

}

on your app component

Login(){
   this.userService.Login(this.userID).subscribe(n=>{
       alert('your name is'+n)
   });
}

if you have no other problems in your code it should work

in case it doesn't work you can do a try catch and show us the error

Login(){
   try{
      this.userService.Login(this.userID).subscribe(n=>{
         alert('your name is'+n)
      });
   }catch(error) console.log(error)
   
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks but in the first option it still didnt work, in the second option it wrote httpError response
I think there is no 'first option' as those are 3 parts of "one option"
show us all the mistakes
1

I don't see an issue with the code in itself. Here's a simple implementation using a subscribe with a get method.

According to your comments, the error probably lies in the response from the server

Comments

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.