为什么从浏览器按 F5 时 Angular5 会调用 api?

Why Angular5 calls a api when F5 from browser?

我是 angularjs(使用 v5)的初学者,我正在尝试进行路由。嗯,路由工作正常,但它仅在我们按 f5 时才加载数据。

我有一个登录页面。单击登录按钮时,Api 被调用,它 returns 是真实用户的令牌。 如下:

登录组件

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'])
    });
  }

在此方法中,在 api 成功返回令牌后,用户被发送到欢迎页面并呈现欢迎页面,但没有该用户的任何数据。 也就是说,它显示了一个空的 page.This 发生,因为 "api" 没有被所有 header 调用,其中包括授权和 berarer header。

但是在从浏览器执行 f5 时,它将 headers 传递给 api 并成功 returns 数据。

以下是欢迎部分。

 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);
    };
  }
}

并且loadUsers调用userservice调用api。这是用户服务:

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);
    }

}

根据我的说法,const 变量可能是导致问题的原因,但我从 angularjs live Example

那里得到了这种方法

你能指出我哪里做错了吗?

是的,问题是 const,不,你不是被迫这样做的。

发生的情况是,您在创建服务时声明 headers,这是在您的应用程序开始时,而您需要在调用之前立即创建它。

试试这个服务:

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);
}

您可以在 UserSrevice 中创建一个获取 httpOptions 的方法:

@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', this.getHttpOptions()).catch(this.handleError);
    }

    getHttpOptions() {
        return {
            headers: new HttpHeaders({
                'Content-Type':  'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            })
        }
    }
}

You can also use interceptors