如何在 Angular2 中的组件之间传递当前用户?

How to pass current user between components in Angular2?

我花了大约 5 个小时试图学习如何实现可观察对象、主题、行为主题等,但似乎无法完全掌握如何做到这一点。本质上,我有一个登录组件。登录组件调用 auth.service.ts 进行 http 调用以对用户进行身份验证。

成功登录用户后,我转到another.component.ts。我希望 another.component.ts 能够访问 auth.service.ts 文件中的 this.currentUser。

代码:

** login.component.ts **

// this works -> authenticates user and sends to home page
this.authService.authenticateUser(this.loginUser)
  .subscribe((response) => {
    this.router.navigate([/'homePage']);
  });



** auth.service.ts **

  public signedInUser = new BehaviorSubject<User>(null);

  // gets called when user submits login form
  authenticateUser(user) {
    let route = "http://localhost:3000/login";

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post(route, user, { headers: headers })
      .map((response) => {
        ??? set this.signedInUser ???
        return response.json();
      })
      .catch((error)  => {
        return Observable.throw(error.json());
      })
  }


  // I tried implementing this functionality
  // I think one of the issues is I can't figure out where
  // to put this.signedInUser.next();

  subscribeToCurrentUser() {
    return this.signedInUser.asObservable();
  }




** another.component.ts **
// I want access to this.authService.signedInUser
   it currently is undefined
   I even added {{ currentUser.firstName | async }}
   and it didn't work

我似乎不太明白如何将所有这些拼凑在一起。任何帮助或见解将不胜感激。

====找到答案====

*** login.component.ts ***
this.authService.authenticateUser(this.loginUser);

** auth.service.ts **

  public signedInUser = new BehaviorSubject<User>(null);

  // gets called when user submits login form
  authenticateUser(user) {
    let route = "http://localhost:3000/login";

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http.post(route, user, { headers: headers })
      .map((response) => {
        return response.json();
      })
      .catch((error)  => {
        return Observable.throw(error.json());
      })
      .subscribe((response) => {
        this.currentUser.setCurrentUser(response.user);
      })
  }

  getCurrentUser() {
    return this.signedInUser.asObservable();
  }

  setCurrentUser(user) {
    this.currentUser.next(user);
  }




** another.component.ts **
this.authService.getCurrentUser()
    .subscribe((user) => {
       this.currentUser = user;
    })