Angular 5.如何更新组件中的服务数据?

时间:2018-03-27 19:38:18

标签: angular login observable angular5 auto-update

我有一个登录服务和组件,它们都与firebase一起使用,并不重要,只是解释了发生了什么。

所以!我有使用login / signIn表单的组件,它与auth.service.ts配合得很好。我还有另一个组件user-data.component.js,其中始终显示位于页面顶部。我想在auth.service.ts(通过切换auth.component.ts中的帐户)中显示用户信息每次用户对象更改以显示用户图像。

很难解释,但我希望有人可以解释我如何解决这个问题。谢谢!

auth.service.ts

import {
  Injectable
} from '@angular/core';

import {
  AngularFireAuth
} from 'angularfire2/auth';
import * as firebase from 'firebase/app';

import {
  Observable
} from 'rxjs/Observable';

@Injectable()
export class AuthService {
  user: Observable < firebase.User > ;

  constructor(private firebaseAuth: AngularFireAuth) {
    this.user = firebaseAuth.authState;
  }

  signup(email: string, password: string) {
    this.firebaseAuth
      .auth
      .createUserWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Success!', value);
      })
      .catch(err => {
        console.log('Something went wrong:', err.message);
      });
  }

  login(email: string, password: string) {
    this.firebaseAuth
      .auth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!', value);
      })
      .catch(err => {
        console.log('Something went wrong:', err.message);
        alert('No user with current data')
      });
  }

  logout() {
    this.firebaseAuth
      .auth
      .signOut();
  }

}

user-data.component.js (这里我尝试更新用户...)

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../shared/services/auth/auth.service';
import { AngularFireAuth } from 'angularfire2/auth';

@Component({
  selector: 'app-user-data',
  templateUrl: './user-data.component.html',
  styleUrls: ['./user-data.component.css']
})
export class UserDataComponent implements OnInit {

  photoUrl;

  ngOnInit() {
      this.authService.user.subscribe(user => {
        this.photoUrl = user.photoURL;
      });
      this.afAuth.authState.subscribe(user => {
        this.photoUrl = user.photoURL;
      });
  }

  constructor(public authService: AuthService, public afAuth: AngularFireAuth) {

  }

}

auth.component.ts (我不知道它是否真的需要,但是)

import { Component } from '@angular/core';
import { AuthService } from '../shared/services/auth/auth.service';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.css']
})
export class AuthComponent  {

  currentUser;

  constructor(public afAuth: AngularFireAuth, public authService: AuthService) {
  }

  googleLogin() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    this.afAuth.authState.subscribe(user => {
      this.currentUser = user;
    });
  }

  // FireBase login
  email: string;
  password: string;


  signup() {
    this.authService.signup(this.email, this.password);
    this.email = this.password = '';
    this.authService.user.subscribe(user => this.currentUser = user);
    console.log(this.currentUser);
  }

  login() {
    this.authService.login(this.email, this.password);
    this.email = this.password = '';
    this.authService.user.subscribe(user => this.currentUser = user);
    console.log(this.currentUser);

  }

  logout() {
    this.authService.logout();
  }

}

1 个答案:

答案 0 :(得分:1)

Observable支持在应用程序中的发布者和订阅者之间传递消息。 以下是代码段:

<强> auth.service.ts

/*getUserInfo function for publishing values between components
*/
private userInfoSource = new Subject<string>();
userInfo$ = this.userInfoSource.asObservable();

getUserInfo(info: string) {
   this.userInfoSource.next(info);
}

<强> auth.component.ts

/* Pass user information every time when user object changes
*/
this.authService.getUserInfo(info);

用户-data.component.ts

import {Subscription} from 'rxjs/Subscription';
...
subscription: Subscription
...
constructor(private authService: AuthService,..) {
   /*subscribing userInfo$ observable to consume values. 
     It start listening when getUserInfo is trigger in auth.component.ts
   */
    this.subscription = authService.userInfo$.subscribe(
      info => {
        console.log(info);
    });
  }
ngOnDestroy() {
    // Unsubscribe an observable to prevent memory leak when component destroyed
    this.subscription.unsubscribe();
  }

价: https://angular.io/guide/observables | https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service