Angular with RxJS:确保使用http.get的服务构造函数在调用方法之前完成

问题描述 投票:0回答:3

在Angular 6中,我有一个ConfigService,需要构造函数才能完成工作:

import { HttpClient, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, Subscribable, Subscription } from "rxjs";

@Injectable()
export class ConfigService {
    public configKeys: any;

    constructor(private http: HttpClient) {
        this.http.get('config/config.json').subscribe(
            data => {
                this.configKeys = data;
            },
            (err: HttpErrorResponse) => {
                console.log (err.message);
            }
        );
    }

    getDocBaseRoute() :string{
        return this.configKeys.docBaseRoute;
    }

    getAuthenticationBaseRoute() :  Subscription {
        return this.configKeys.authenticationBaseRoute;
    }
}

当我尝试调用服务的方法时会触发一个问题:

this.baseUrl = this.configservice.getAuthenticationBaseRoute();

实际上在这一刻configKeys未定义所以return this.configKeys.authenticationBaseRoute;抛出一个错误。

那么你可以帮助我知道在调用服务方法之前我怎么能确定构造函数已经完成了?

angular rxjs angular6
3个回答
2
投票

您应该始终使用RxJS才能正常工作。

import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { shareReplay, map } from 'rxjs/operators';

@Injectable()
export class ConfigService {
    private configuration: Observable<any>;

    constructor(private http: HttpClient) { }

    getDocBaseRoute(): Observable<string> {
        return this.getConfiguration().pipe(map(data => data.docBaseRoute));
    }

    getAuthenticationBaseRoute(): Observable<any> {
        return this.getConfiguration().pipe(map(data => data.authenticationBaseRoute));
    }

    private getConfiguration(): Observable<any> {
        if(!this.configuration) {
            this.configuration = this.http.get('config/config.json').pipe(
                catchError((error: HttpErrorResponse) => console.log(err.message)),
                shareReplay()
            );
        }

        return this.configuration;
    }
}

请注意,我存储Observable,而不是属性中的结果。如果你不这样做并多次调用getConfiguration(),那么由于时间安排,可能会发生多次HTTP调用。使用RxJS shareReplay操作符对此也很重要。

用法:

this.configservice.getAuthenticationBaseRoute().subscribe(baseRoute => this.baseUrl = baseRoute);

0
投票

你无法做到这一点,这将违背RxJS的概念。

在我看来,这更像是一个概念问题,你可以有不同的解决方案来处理这个问题:

  1. configKeys定义一个默认值,以便getAuthenticationBaseRoute永远不会失败。
  2. 处理在configKeysnullgetAuthenticationBaseRoute的情况,让它返回undefined。但你必须处理这种情况,你可以调用getAuthenticationBaseRoute
  3. getAuthenticationBaseRoute中定义configKeys之前,调用ConfigService无法调用的组件/服务/任何内容。

0
投票

好的,我找到了一种方法:使用toPromise()将transforme observable转换为promise

import { HttpClient, HttpHeaders, HttpErrorResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable()
export class ConfigService {
    public configKeys: any;

    constructor(private http: HttpClient) {
    }

    async getGestionDocumentBaseRoute(): Promise<string> {
        await this.initialize();
        return this.configKeys.gestionDocumentBaseRoute;
    }

    private async initialize(): Promise<boolean> {
        if (!this.configKeys) {
            await this.http.get('config/config.json').toPromise()
                .then(
                    data => {
                        this.configKeys = data;
                    }
                )
                .catch(
                    (err: HttpErrorResponse) => {
                        console.log(err.message);
                        return false;
                    }
                );
        }
        return true;
    }

    async getAuthenticationBaseRoute(): Promise<string> {
        await this.initialize();
        return this.configKeys.authenticationBaseRoute;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.