代码之家  ›  专栏  ›  技术社区  ›  cup_of

typescript函数返回未定义

  •  1
  • cup_of  · 技术社区  · 6 年前

    你好,我有一个方法在下面的类中:

    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
      }
    
    }
    

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

    谢谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Vikas RyanSand20    6 年前

    你正在和 async programming 您不能暂停代码的执行,您的订阅将在将来得到解决,但您不能预测何时。 console.log() subscribe 在解决订阅之前执行,因此未定义
    控制台.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}}
    

    或者你可以用 async pipe
    AsyncPipe接受 observable 或者一个承诺,一个电话 订阅 或者附加一个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

        2
  •  1
  •   Sagar Kharab    6 年前
     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; //
    

    这里有一个异步调用。由于您在解析或返回调用之前返回值,因此在 this.searchItems 因为您使用的是对服务器或数据库的调用,所以使用Observable来利用Angular的Promise概念。