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

时间:2017-11-24 18:07:12

标签: angular rxjs

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

应用程序集管的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
  }

0 个答案:

没有答案