Angular / TS-如何从组件到服务调用函数并获取返回值

时间:2018-09-20 16:10:40

标签: angular typescript google-cloud-firestore angularfire5

我有一个在其自身服务中调用“ getUserDocInfo()”的组件。我该如何调用该函数,然后将返回的数据用于进一步的代码?

我的组件

 getToken(){
    this.userService.getUserDocInfo();
    // once this is called I would like to use some of the values in the returned data
  }

我的服务

getUserDocInfo() {
    this.getUserInfo().then(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      this.user.subscribe(value => {
        const data = value.payload.data();
      });
    })
  }

 async getUserInfo() {
    const user = await this.authService.isLoggedIn()
    if (user) {
      this.userID = user.uid;
    } else {
      // do something else
    }
  }

在此对最佳做法的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

一种实现方法是实现将传递方法参数的回调。像这样的东西。

getUserDocInfo(callback) {
    this.getUserInfo().then(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      this.user.subscribe(callback);
    })
  }

getToken(){
    this.userService.getUserDocInfo((value) => {
        console.log(value.payload.data());
    });
  }

您也可以返回Observable并在组件上下文中进行订阅,然后可以根据需要处理订阅。

import { Observable } from 'rxjs/Observable/';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

@Injectable()
export class AlertService {

  //constructor and properties...

  getUserDocInfo(): Observable<any> {
    Observable.fromPromise(this.getUserInfo()).mergeMap(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      return this.user.map(user => user);
    });
  }
}

@Component(...)
export class MyComponent implements OnDestroy {

  subscriptions: Array<Subscription> = new Array;

  //constructor

  getToken(){
    const sub = this.userService.getUserDocInfo().subscribe((value) => {
        console.log(value.payload.data());
    });
    this.subscriptions.push(sub);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }
}