如何在每次服务调用之前运行方法?(Angular 7)

时间:2019-04-09 13:09:28

标签: javascript angular frontend

我正在尝试从本地存储中获取“有效载荷”,而不是执行服务方法。 实际上,我正在尝试在构造函数方法上执行此操作,但有时在调用方法时未设置变量“ this.payload”。

这是我的代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as Globals from '../../globals';
import { Observable, of } from 'rxjs';
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable({
    providedIn: 'root'
})
export class RechargesService {

    public payload;

    constructor(
        private http: HttpClient,
        public localStorage: LocalStorage
    ) {
        this.localStorage.getItem("payload").subscribe((payload) => {
            this.payload = payload;
        })
    }


    list(): Observable<any> {
        return this.http.post(Globals.url_api + "recharges/list", {
            // Sometimes this.payload isn't setted, i don't know why
            "payload": this.payload
        });
    }
}

正确的方法是什么?我知道在控制器中,我不应该在构造函数方法上写任何东西,但是在服务中是正确的吗?

3 个答案:

答案 0 :(得分:2)

如果要在每次list()调用之前获取有效负载,可以按照以下步骤进行操作:

首先创建一个方法,该方法返回一个从本地存储获取值的可观察对象,然后使用switchMap返回一个内部可观察对象(即HTTP get请求)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as Globals from '../../globals';
import { Observable, of} from 'rxjs';
import { tap, switchMap } from 'rxjs/operators';
import { LocalStorage } from '@ngx-pwa/local-storage';

@Injectable({
    providedIn: 'root'
})

export class RechargesService {

public payload;

    constructor(
        private http: HttpClient,
        public localStorage: LocalStorage
    ) {

    }

     getPayload = () => {

        return this.localStorage.getItem("payload").pipe(tap(payload => this.payload = payload)); // <--- the tap() may be redundant here. you can simply get payload in list() method

     }


    list(): Observable<any> {

        return this.getPayload().pipe(
            switchMap(payload => {
               return this.http.post(Globals.url_api + "recharges/list", {"payload": this.payload})  // <--- You can use payload instead of this.payload since localStorage already returns payload
            })
        );
    }

}

switchMap:https://www.learnrxjs.io/operators/transformation/switchmap.html

执行/点击:https://www.learnrxjs.io/operators/utility/do.html

答案 1 :(得分:1)

创建一个getPayload函数tp以获取本地存储数据,并在列表函数中使用switchMap将getPayaload数据传递给api。

getPayload(){
    return this.localStorage.getItem("payload");
}

list(payload): Observable<any> {
    return getPayload().pipe(
        switchMap(
            (payload) => {
                return this.http.post(Globals.url_api + "recharges/list", {
                    payload
                })
            },
        )
    );
}

答案 2 :(得分:0)

使用forkJoin运算符

https://www.learnrxjs.io/operators/combination/forkjoin.html

forkJoin(
      this._myService.makeRequest('Request One', 2000),
      this._myService.makeRequest('Request Two', 1000),
      this._myService.makeRequest('Request Three', 3000)
    )
    .subscribe(([res1, res2, res3]) => {
      this.propOne = res1;
      this.propTwo = res2;
      this.propThree = res3;
    });