How to return value inside subscribe Angular 4

前端 未结 4 1962
梦毁少年i
梦毁少年i 2020-12-30 22:07

I\'m new to observables in angular. I have a problem wanting to return a value inside a subscribe method. I have the following method (getFirebaseData(idForm:string):o

相关标签:
4条回答
  • 2020-12-30 22:11

    To solve this I would create a property totalQuestions$ an observable

    In the TS file

    totalQuestions$ = this.getFirebaseData(idForm + "/Metadatos").pipe(
      map(items => items.reduce((prev, {Total}) => prev + Total), 0)))
    )
    

    And Now in your template you can use async pipe

    <span>{{ totalQuestions$ | async }}</span>
    

    If you would like to use the variable in your TS file, then you can use combination operators like forkJoin or combineLatest to access this value

    newVariable$ = combineLatest([totalQuestions$, ...]).pipe(
      map(([totalQuestions, ... ]) => {
        // Perform an operation here and return a value
      })
    )
    
    0 讨论(0)
  • 2020-12-30 22:12

    I made a live example. You do not need to fire the subscription to make transformations to the array or reduce some object to a single value, here is my approached. Your service

    getTotalQuestions(idForm: string): Observable<any> {
        return this.getFirebaseData(`${idForm}/Metadatos`)
            .pipe(map(items => items
                .map(item => item.Total)
                .reduce((a, b) => a+b), 0));
    }
    

    Your component

    this.service.getTotalQuestions('id')
        .subscribe(totalQuestions => console.log(totalQuestions));
    
    0 讨论(0)
  • 2020-12-30 22:21

    You can't directly return totalQuestions like that, you need to use a subject to achieve that.

    getTotalQuestions(idForm:string): Observable<string> {
    let totalQuestions:number;
    var subject = new Subject<string>();
    this.getFirebaseData(idForm+"/Metadatos")
    .subscribe(items => {
        items.map(item => {
    
          totalQuestions=item.Total;
          console.log(totalQuestions);
          subject.next(totalQuestions);
        });
      }
    );
      return subject.asObservable();
    }
    

    Usage: getTotalQuestion(idForm).subscribe((r)=>console.log(r))

    0 讨论(0)
  • 2020-12-30 22:21

    Observable runs when you subscribe to it and what return from subscription is always a subscription object like setInterval. first sample: because this is a async call, second console.log won't wait for subscribe to finish before it executes.

    getTotalQuestions(idForm: string) {
      let totalQuestions: number;
      return this.getFirebaseData(idForm + "/Metadatos").pipe(
         map(items =>
          items.map(item => {
            totalQuestions = item.Total;
            console.log(totalQuestions);
          });
        ));
    }
    
    getTotalQuestions('231').subscribe(console.log)
    
    0 讨论(0)
提交回复
热议问题