gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:05:59 26 4
gpt4 key购买 nike

在执行服务方法之前,我正在尝试从本地存储获取“有效负载”。实际上,我正在尝试在构造函数方法上执行此操作,但有时在调用方法时未设置变量“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
});
}
}

正确的做法是什么?我知道在 Controller 中,我不应该在构造方法上写任何东西,但在服务中它是正确的吗?

最佳答案

如果你想在每次 list() 调用之前获取 payload,你可以像下面这样:

首先创建一个方法返回一个从本地存储获取值的可观察对象,然后使用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

关于javascript - 如何在每次服务调用之前运行一个方法?(Angular 7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com