angular - 如何从 Observable 中检索值以用于服务 API 调用
问题描述
我有一个使用 ngrx-store 的 Angular 应用程序。我的功能组件有以下文件
<componentname>.actions.ts
<componentname>.effects.ts
<componentname>.model.ts
<componentname>.module.ts
<componentname>.reducer.ts
<componentname>.state.ts
<componentname>.selectors.ts
<componentname>-routing.module.ts
我是 Observables 和 NGRX 存储的新手,我需要一些帮助来从存储中检索一个值(emailAddress),然后在服务 API 调用中使用。在服务方法中,我可以订阅和控制台记录该值,但是当进行服务调用时,该值是空白的,所以我没有取回数据。
如何订阅 emailAddress 选择器并同时调用服务 API 以确保该值存在。商店中的电子邮件地址仅在用户登录时存储一次,该值永远不会改变。
我的组件
import { selectStrava } from "@app/strava/strava.selector";
import { selectEmailAddress } from "@app/core/auth/auth.selectors";
@Component({
selector: "srm-strava",
templateUrl: "./strava.component.html",
styleUrls: ["./strava.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class StravaComponent implements OnInit {
@Input()
strava$: Observable<Strava>;
constructor(private stravaStore: Store<IStravaState>) {
this.strava$ = this.stravaStore.pipe(select(selectStrava));
}
ngOnInit() {
this.stravaStore.dispatch(new GetStravaAuthorization());
}
}
我的组件选择器
import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromAppStore from "@app/core/auth/auth.reducer";
import { IStravaState } from './strava.state';
export const selectStravaState = createFeatureSelector<IStravaState>('strava');
export const state = createSelector(selectStravaState, (stravaState: IStravaState) => stravaState);
export const selectStrava = createSelector(state, (stravaState: IStravaState) => stravaState.strava);
我的 API 服务中的方法
constructor(http: HttpClient, notificationService: NotificationService, appState: Store<AppState>) {
this.http = http;
this.notificationService = notificationService;
this.appState = appState;
}
public getStravaAuthorization(): Observable<Strava> {
this.emailAddress$ = this.appState.pipe(select(selectEmailAddress));
//the following outputs to the console OK
this.emailAddress$.subscribe(res => { console.log(res) });
//the email address is blank on the next call
let getStravaApi = `${AppSettings.CONTACTS_API_HOST}employee/strava?emailaddress=${this.emailAddress$}`;
return this.http.get<Strava>(getStravaApi).pipe(
tap(result => console.log('getStravaAccess: executed with email ')),
map(result => result));
};
我的效果如下
@Effect()
getStravaAuthorization$ = this.actions$.pipe(
ofType<GetStravaAuthorization>(StravaActionTypes.GetStravaAuthorization), mergeMap(() => this.stravaService.getStravaAuthorization()
.pipe(map((strava: Strava) => new GetStravaAuthorizationSuccess(strava))))
);
从存储中检索值的电子邮件地址选择器是
export const selectEmailAddress = createSelector(
selectAuth, (state: AuthState) => {
if ((state.userDetails === null || state.userDetails === undefined))
return "";
else
return state.userDetails.email
;
}
);
我的控制台日志如下
按照建议将代码从服务移动到组件后,我现在在 this.emailAddress$ 上收到一个错误,指出“无法为‘新’表达式类型不匹配选择重载参数 emailAddress 应该具有可分配给字符串的类型,但它具有可观察的类型
更新的组件代码
import { Component, ChangeDetectionStrategy, OnInit, Input } from "@angular/core";
import { Observable } from "rxjs";
import { take } from "rxjs/operators";
import { Store, select } from "@ngrx/store";
import { GetStravaAuthorization } from "@app/strava/strava.actions";
import { Strava } from "@app/strava/strava.model";
import { IStravaState } from "@app/strava/strava.state"
import { AuthState } from "@app/core/auth/auth.model.ts";
import { AppState } from "@app/core/core.state.ts"
import { selectStrava } from "@app/strava/strava.selector";
import { selectEmailAddress } from "@app/core/auth/auth.selectors";
@Component({
selector: "srm-strava",
templateUrl: "./strava.component.html",
styleUrls: ["./strava.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class StravaComponent implements OnInit {
@Input()
strava$: Observable<Strava>;
@Input()
emailAddress$: Observable<string>;
constructor(private stravaStore: Store<IStravaState>, private appState: Store<AppState>) {
this.strava$ = this.stravaStore.pipe(select(selectStrava));
}
ngOnInit() {
this.emailAddress$ = this.appState.pipe(select(selectEmailAddress));
this.stravaStore.dispatch(new GetStravaAuthorization(this.emailAddress$));
}
}
更新代码
我的组件
ngOnInit() {
this.appState
.pipe(
select(selectEmailAddress),
first()
)
.subscribe((emailAddress) => {
this.stravaStore.dispatch(new GetStravaAuthorization(emailAddress)); //dispatch action with the payload containing email address
});
}
我的效果
@Effect()
getStravaAuthorization$ = this.actions$
.pipe(
ofType<GetStravaAuthorization>(StravaActionTypes.GetStravaAuthorization),
mergeMap((action) => {
// passing the action's payload (email address) below to service
return this.stravaService.getStravaAuthorization(action.payload);
},
map((strava: Strava) => new GetStravaAuthorizationSuccess(strava)))
);
我的服务
public getStravaAuthorization(emailAddress): Observable<Strava> {
let getStravaApi = `${AppSettings.CONTACTS_API_HOST}employee/strava?emailaddress=${emailAddress}`;
return this.http.get<Strava>(getStravaApi).pipe(
tap(result => console.log('getStravaAccess: executed with emaiL address ')),
map(result => result));
}
行动
export class GetStravaAuthorization implements Action {
readonly type = StravaActionTypes.GetStravaAuthorization;
constructor(public payload: string) { }
}
export class GetStravaAuthorizationSuccess implements Action {
readonly type = StravaActionTypes.GetStravaAuthorizationSuccess;
constructor(public payload: Strava) { }
}
需要指出的其他内容 EmailAddress 不是 IStraviaState 的一部分
import { Strava } from "@app/strava/strava.model";
export interface IStravaState {
strava: Strava;
}
export const initialStravaState: IStravaState = {
strava: null
};
export class Strava {
stravaAuthorization: StravaAuthorization
}
export class StravaAuthorization {
entityId: string;
accessToken: string;
refreshToken: string;
isAuthorized: boolean;
}
我现在看到的更新代码的错误
解决方案
看起来您在构建请求时试图将 Observable 用作字符串值。
let getStravaApi = `${AppSettings.CONTACTS_API_HOST}employee/strava?emailaddress=${this.emailAddress$}`;`
有几种方法可以实现这一点,我将分享 async/await 路线。
.toPromise()
您可以通过使用该方法将 observable 转换为 promise 来等待 observable 的结果。
public async getStravaAuthorization(): Observable<Strava> {
...
const emailAddress = await this.emailAddress$.toPromise();
...
}
推荐阅读
- rust - 将petgraph点写入文件
- javascript - 使用 Vue 和 webpack 钩住 HMR
- python - 使用python在硒中打开谷歌浏览器时出错
- java - Http Post的响应码是415,如何让响应码变成200
- android - 如何提取消息标题和正文形式 OneSignal 推送通知 Flutter
- php - 获取包含父母、孩子和元数据的帖子类型
- multicast - Ghost 12 - 不能跨子网多播
- python - pip install regex 无法在 Anaconda python3.6.9 virtualenv 上构建
- go - 如何在 Go 中正确编写 JVM AES/CFB8 加密
- python-3.x - TypeError: unhashable type: 'numpy.ndarray' 合并来自 BigQuery 的 pandas 数据帧时