如何返回可观察结果

时间:2018-07-13 00:49:01

标签: angular typescript angular6

我只想将预订的结果(是一个数组)返回给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方法以返回订阅的值(它是一个数组)

4 个答案:

答案 0 :(得分:3)

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()。

答案 1 :(得分:0)

通常,您返回Observable并在实际需要的地方订阅它。

答案 2 :(得分:0)

您必须返回这样的数据

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

答案 3 :(得分:0)

所以我终于明白了。 首先,我在服务中创建了一个返回诺言

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

然后在我的主要输入方法(被调用的实际函数)中,我使用了asyc await函数来等待promise,然后继续执行代码

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

感谢大家的贡献,给了我更多阅读的机会,所以我也学到了更多!