加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – typescript函数返回undefined

发布时间:2020-12-17 07:56:00 所属栏目:安全 来源:网络整理
导读:您好,我在下面的课程中有一个方法: export class SearchService { userUID: string; searchItems: any; private searchesCollection: AngularFirestoreCollection; constructor( private db: AngularFirestore,private afAuth: AngularFireAuth,) { } getSe
您好,我在下面的课程中有一个方法:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读