如何访问角度模板中可观察变量的属性?

ish*_*007 1 rxjs angular

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { AngularFireAuth } from 'angularfire2/auth';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class AuthService {
  public currentUser;
  constructor(private afAuth: AngularFireAuth,
    private router: Router) {
  }
}
Run Code Online (Sandbox Code Playgroud)

app-header-navbar-user.component.ts

import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { AuthService } from '../../../shared/services/auth.service';

import { environment } from '../../../../environments/environment';
import { constants } from '../../../../constants';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Component({
  selector: 'app-header-navbar-user',
  template: `
  <div (click)="change()">CHANGEdisplayName</div>
  <div>{{ CUser$.displayName }}</div>
  `,
  changeDetection: ChangeDetectionStrategy.Default
})
export class AppHeaderNavbarUserComponent {
  public CUser$: Observable<any> =Observable.of(this.authService.currentUser);

  constructor(private authService: AuthService) {
  }

  ngOnInit() {
    this.authService.currentUserObs$.subscribe((x) => {
      console.log("signInUser:ngOnInitIN:" + x);//always undefined here no matter what. 
    });
  }

  change() {
    if (!this.authService.currentUser)
           this.authService.currentUser = {};
    this.authService.currentUser['displayName'] = "YOMAN";//breaks here saying invalid property
  }
Run Code Online (Sandbox Code Playgroud)

acd*_*ior 6

尝试使用?(elvis) 运算符:

<div>{{ (CUser$ | async)?.displayName }}</div>
Run Code Online (Sandbox Code Playgroud)

另外,我看到您正在尝试更新 的值this.currentUser并期望 的值发生this.CUser$变化。

你需要的是 make this.CUser$be BehaviorSubject- 而不是一个简单的Observable- 并且要更新它,调用.next(<new user>).

一个完整的组件/示例如下:

import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Component({
  selector: 'app-root',
  template: `
  <h1>Display Name: "{{ (CUser$ | async)?.displayName }}"</h1>

  <button (click)="change()">CHANGE!</button>
  `
})
export class AppComponent {
  private currentUser;

  // here, the value of this.currentUser is used as initial value of the observer CUser$
  // to change the value of CUser$, you must call CUser$.next(NEW VALUE).
  public CUser$: BehaviorSubject<any> = new BehaviorSubject<any>(this.currentUser);


  change() {
    this.currentUser = new User('Bob Nelson ONE'); // has no effect, just changes the currentUser

    this.CUser$.next(new User('Bob Nelson TWO')); // updates the CUser$
  }
}

class User  {
  constructor(public displayName: string) {}
}
Run Code Online (Sandbox Code Playgroud)

Plunker 链接在这里

  • 实际上,我想我明白你的问题所在。您正在尝试更新 `this.CUser$`。我更新了答案。 (2认同)