微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular – typescript函数返回undefined

您好,我在下面的课程中有一个方法
export class SearchService {
  userUID: string;
  searchItems: any;
  private searchesCollection: AngularFirestoreCollection;

  constructor(
    private db: AngularFirestore,private afAuth: AngularFireAuth,) {
  }

  getSearches() {
    this.afAuth.authState.subscribe(user => {
      this.userUID = user['uid'];
      this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`);
      this.searchItems = this.searchesCollection.valueChanges().subscribe(data => {
        console.log(data); // works
        return data;
      });
    });
    console.log(this.searchItems); // undefined
    return this.searchItems; //undefined
  }

}

我的问题是return语句,它返回undefined.它上面几行的console.log(data)返回我想要的值.我想知道为什么我会变得不确定.这可能是一个范围问题,但我似乎无法弄明白.它可能是一个我忽略的简单错误.有什么建议么?

谢谢!

您正在使用 async programming ,您无法暂停代码的执行,您的订阅将在未来解决,但您无法预测何时.订阅之外的console.log()在您的订阅解决之前执行,这就是为什么它是未定义的,并且在订阅被解析之后调用subscribe回调中的console.log().为了更好地理解,请调用 this.
你可以做的是你可以将值存储在类属性中并在模板中访问它.
getSearches() {
    this.afAuth.authState.subscribe(user => {
      this.userUID = user['uid'];
      this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`);
   this.searchesCollection.valueChanges().subscribe(data => {
        console.log(data); // works
         this.searchItems=data;
      });
    });
    console.log(this.searchItems); // undefined
    return this.searchItems; //undefined
  }

HTML

{{searchItems?.//property}}

或者您可以使用异步管道
AsyncPipe接受一个observable或promise作为参数,调用subscribe或附加一个then处理程序,然后在将它传递给调用者之前等待异步结果.

getSearches() {
        this.afAuth.authState.subscribe(user => {
          this.userUID = user['uid'];
          this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`);
       this.searchItems=this.searchesCollection.valueChanges();

      }

HTML

<ng-container *ngFor="let item of searchItems|async">
      {{item?.//property}}
<ng-container>

LIVE DEMO

原文地址:https://www.jb51.cc/angularjs/143587.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐