角度生命周期,ngOnInit之后获取的数据

时间:2018-04-09 14:31:54

标签: angular lifecycle

app.component.ts:

import { Component, OnInit, Inject } from '@angular/core';

import { UserService } from './services/user.service';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(
    private userService: UserService,
    private authService: AuthService
  ) {
  }

  public ngOnInit() {
    const currentToken = localStorage.getItem('xoAuthToken');
      if (currentToken) {
        const data = { token: currentToken };
        this.userService.verifyToken(data)
          .subscribe((response: any) => {
            if (response.result && response.user) {
              this.authService.authenticate(response.user);
            }
          });
      }
  }
}

auth.service.ts:

public authenticated = new Subject();

public authenticate(user) {
  this.user = user;
  this.authenticated.next(this.user);
}

public getUser() {
  return this.user;
}

问题是,当我尝试从AuthService获取另一个组件中的用户信息时:

some.component.ts:

public ngOnInit() {
  const user = this.authService.getUser();
  console.log(user);
}

它尚未初始化,所以我应该在哪里检查localStorage是否有令牌并发出http请求,以便在OnInit的任何组件中,数据已经可用?

1 个答案:

答案 0 :(得分:0)

使用该行为主题

public authenticated = new BehaviorSubject(null);

public authenticate(user) {
  // Auth function : return undefined if the user failed to login.
  this.authenticated.next(this.user);
}

在您的组件中:

public ngOnInit() {
  this.authService.authenticated.subscribe(user => {
    if (user === null) { /* not logged yet */ }
    else if (user === undefined) { /* failed to log in */ }
    else if (!!user) { /* is logged */ }
  });
}

每次在BSubject上调用next时,都会触发此订阅。