簡體   English   中英

如何返回可觀察結果

[英]How to return the result of an observable

我只想將訂閱的結果(是一個數組)返回給getData函數。

我有一個依賴於getData方法的返回值起作用的組件

import { ReportsService } from './../../../../../../services/reports.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-cardyesterday',
  templateUrl: './cardyesterday.component.html',
  styleUrls: ['./cardyesterday.component.css']
})
export class CardyesterdayComponent implements OnInit {
  salesCounter: any;
  amountCounter: any;
  changeCounter: any;
  changePeople: any;
  constructor(private report: ReportsService) { }

  ngOnInit() {
    const d = this.report.getData();
  }


}

這是服務

import { AuthService } from './auth.service'; 
import { Injectable } from '@angular/core';

@Injectable({ 
    providedIn: 'root' 
}) 
export class ReportsService { 
    user: String; 
    constructor(private authService: AuthService) { } 
    getData() { 
        this.authService.getSales().subscribe(d => { 
            this.user = d.data; 
        }, 
        error => console.log(`error is ${error}`), 
        this.hh.bind(this)); 
        return this.user 
    } 

    hh() { 
        return this.user 
    } 
}

所以我如何在ReportsService中獲取getData方法以返回subscription的值(它是一個數組)

import { AuthService } from './auth.service'; 
import { Injectable } from '@angular/core';

@Injectable({ 
    providedIn: 'root' 
}) 
export class ReportsService { 
    user: String; 
    constructor(private authService: AuthService) { } 
    getData() { 
        return this.authService.getSales();
    } 

    hh() { 
        return this.user 
    } 
}

零件

import { ReportsService } from './../../../../../../services/reports.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-cardyesterday',
  templateUrl: './cardyesterday.component.html',
  styleUrls: ['./cardyesterday.component.css']
})
export class CardyesterdayComponent implements OnInit {
  salesCounter: any;
  amountCounter: any;
  changeCounter: any;
  changePeople: any;
  constructor(private report: ReportsService) { }

  ngOnInit() {
    subscription = this.report.getData().subscribe(data => { do something});
  }        
}

隨時隨地致電subscription.unsubscribe()。

通常,您返回Observable並在實際需要它發出的數據的任何位置進行訂閱。

您必須這樣返回數據

getData(): Observable<YOUR_DATA_TYPE> { 
        this.authService.getSales().subscribe(d => { 
            return this.user = d.data; 
        }, 
etc..

然后在您的TS文件中

this.report.getData().subscribe( (response) => {
   this.user = response.data;
});

所以我終於明白了。 首先,我在服務中創建了一個返回承諾的方法

fetcher() {
    return new Promise((resolve, reject) => {
      this.authService.getSales().subscribe(d => {
        this.server = d.data;
        resolve();
      });
    });
  }

然后在我的主進入方法(被調用的實際函數)中,我使用了asyc await函數來等待諾言,然后繼續執行代碼

async getSalesCounter(n) {
    const data = this.dateService.getDate();
    const date = data.split('|')[0];
    const day = data.split('|')[1];
    const month = data.split('|')[2];
    const year = data.split('|')[3];
    const finalUdate = parseInt(`${year}${month}${date}`, 10);

    await this.fetcher();
    const temp = {
      salesCounter: 0,
      amountCounter: 0,
      changeCounter: 0,
      changePeople: 0,
      products: []
    };
    this.server.forEach(serv => {
      const Sdate = serv.date.split('|')[0];
      const Sday = serv.date.split('|')[1];
      const Smonth = serv.date.split('|')[2];
      const Syear = serv.date.split('|')[3];
      const finalServerDate = parseInt(`${Syear}${Smonth}${Sdate}`, 10);

      const calcResult = finalUdate - finalServerDate;
      if (calcResult === n) {
        temp.salesCounter = this.todaySales();
        temp.amountCounter += serv.price;
        temp.products.push(serv);
        if (serv.change > 0) {
          temp.changeCounter += serv.change;
          temp.changePeople = this.countChange();
        }
      }
    });
    this.salesCounter = temp.salesCounter;
    this.amountCounter = temp.amountCounter;
    this.changeCounter = temp.changeCounter;
    this.changePeople = temp.changePeople;
    const details = {
      salesCounter: this.salesCounter,
      amountCounter: this.amountCounter,
      changeCounter: this.changeCounter,
      changePeople: this.changePeople,
      products: temp.products
    };
    this.salesCounter = 0;
    this.changePeople = 0;
    return details;
  }

謝謝大家的貢獻,給了我閱讀更多的機會,所以我也學到了更多!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM