Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

angular - typescript function returning undefined

Hello I have a method in a the class below:

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
  }

}

My issue is with the return statement, it is returning undefined. The console.log(data) a few lines above it returns the value I want. I am wondering why I am getting undefined. It might be a scoping issue but I cant seem to figure it out. Its probably a simple error I am overlooking. Any suggestions?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...