Angular 4实例字段在代码中已更改,但更改未在模板中反映出来

时间:2017-10-27 12:26:11

标签: angular typescript rxjs

我面临的问题是组件类中实例变量的更改不会反映在我的模板文件中,除非我明确调用ref.detectChanges

signInWithGoogle是我的身份验证服务中的一种方法,我从组件调用google登录

signInWithGoogle(): Observable<User> {
    const observable = Observable.fromPromise(
      this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
    ).concatMap(result => {
      const url = environment.apiEndpoint + '/rest-auth/social/google/';
      const request = { access_token: result.credential.accessToken };
      return this.login(url, request);
    });
    return observable;
  }

  private login(url, request): Observable<User> {
    return this.http
      .post<User>(
        url,
        request
      )
      .concatMap((user: User) => {
        localStorage.setItem(
          environment.constants.STORAGE_USER,
          JSON.stringify(user)
        );
        return Observable.of(user);
      });
  }

以下是我的组件的相关代码段:

export class LoginComponent implements OnInit {
    errorMessage: string;
    request = new LoginRequest();

    googleSignIn($event) {
        $event.preventDefault();
        this.authService.signInWithGoogle().subscribe(
          (user: User) => {
            console.log('logged in');
          },
          err => {
            this.errorMessage = 'Problem while signing in with google';
          }
        );
      }
}

这就是我在模板中使用errorMessage组件文件的方法

<ngb-alert *ngIf="errorMessage" [dismissible]="false" type="danger">
      {{errorMessage}}
</ngb-alert>

1 个答案:

答案 0 :(得分:1)

使用observable代替:

// in component
errorMessage$ = new BehaviorSubject<string>(null);

googleSignIn($event) {
    $event.preventDefault();
    this.authService.signInWithGoogle().subscribe(
      (user: User) => {
        console.log('logged in');
      },
      err => {
        this.errorMessage$.next('Problem while signing in with google');
      }
    );
  }

在模板中使用异步管道:

<ngb-alert *ngIf="errorMessage$ | async as errorMessage" [dismissible]="false" type="danger">
    {{ errorMessage }}
</ngb-alert>