Why Angular5 calls a api when F5 from browser?

Issue

I am a beginner in angularjs(using v5) and I am trying to do routing. Well, routing is working fine but it loads data only when we hit f5.

I have a sign in page. on click of login button, Api gets called and it returns a token for the authentic user.
as below:

Login component

login()
  {
    this.authService.login(this.model).subscribe(m=>{
    this.alertify.success('Logged in successfully');
    localStorage.setItem('token', this.userToken);
    }, error => {
      this.alertify.error(error);
    }, ()=>{
       this.router.navigate(['/welcome'])
    });
  }

In this method, after the token is successfully returned by api, user is sent to welcome page and it renders welcome page but without any data of that user.
That is it shows an empty page.This happens because “api” doesn’t get called by all the headers which include Authorization & berarer header.

But on doing f5 from browser, it pass the headers to api and it success returns data.

and below is the welcome component.

 export class WelcomeComponent implements OnInit {
  users: User[];

  constructor(private userService: UserService, private alertify: AlertifyService) { }

  ngOnInit() {
    this.loadUsers();
  }

  loadUsers()
  {
    alert("Loading users");
    this.userService.getUsers().subscribe(users => this.users = users)
    , error => {
      this.alertify.error(error);
    };
  }
}

and loadUsers call userservice to call api. here is User service:

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    })
  };

  @Injectable()
export class UserService {
baseUrl = environment.apiUrl;

constructor(private httpClient: HttpClient) { }

 getUsers (): Observable<User[]> {
    alert(httpOptions.headers);
      return this.httpClient.get<User[]>(this.baseUrl + 'users', httpOptions).catch(this.handleError);
    }

}

According to me, the const variable might be causing the problem but i have got this methodology from angularjs live Example

Could you please suggest where i am doing wrong?

Solution

Yes, the issue is the const, no, you’re not forced to do that.

What happens is that you declare your headers at your service creation, which is at the start of your application, while you need to create it right before doing the call.

Try this for your service :

getUsers (): Observable<User[]> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    });
  };
  return this.httpClient.get<User[]>(this.baseUrl + 'users', httpOptions).catch(this.handleError);
}

Answered By – user4676340

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.