0

我有一个调用“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
    }
  }

任何有关最佳实践的帮助将不胜感激。

4

1 回答 1

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());
  }
}
于 2018-09-20T16:17:35.057 回答