typescript function returning undefined

前端 未结 2 711
星月不相逢
星月不相逢 2020-12-12 02:45

Hello I have a method in a the class below:

export class SearchService {
  userUID: string;
  searchItems: any;
  private searchesCollection: AngularFirestor         


        
相关标签:
2条回答
  • 2020-12-12 03:25
     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; //
    

    there is an async call in this. Since you are returning the value before your call is resolved or comes back you will not have data in this.searchItems since you are using a call to server or to db, use observable to take advantage of Angular's promise concept.

    0 讨论(0)
  • 2020-12-12 03:26

    You are working with async programming you cannot pause the execution of the code and your subscription will be resolved in future but you cannot predict when. console.log() outside the subscribe is executed before your subscription is resolved that's why it's undefined
    and console.log() inside subscribe call back is invoked after the subscription is resolved.
    Refer this for better understanding.
    what you can do is You can store the value in a class property and access it in your template.

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

    or you can use async pipe
    AsyncPipe accepts as an argument an observable or a promise, calls subscribe or attaches a then handler, then waits for the asynchronous result before passing it through to the caller.

     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

    0 讨论(0)
提交回复
热议问题