Angular 6 - 外化 url

Angular 6 - externalizing url

我正在尝试将 url 和 angular 中的属性外部化 6.

有一个调用第 3 方 URL 来获取数据的服务。

天气-component.html -> weather.component.ts -> weather.service.ts

在我的 weather.service.ts,

public getWeather() {
     // Here I have hardoded the URL and the api key.   
}

我想将其外部化以使其可配置。

不确定如何将其移动到可配置文件并从那里读取。

我想你想做通用服务

你可以有一个 baseHttp.service.ts 并且 weather.service.ts 将扩展 baseHttpservice 以进行 api 调用。

baseHttp.service.ts

@Injectable()
export abstract class BaseHttpService {
    private baseUrl: string = Constants.BASEURL;
    protected method: string;
    protected serviceUrl: string;
    protected headers: Headers;

    constructor(private http: Http) {
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    call(params: any) {

        let url: string = this.setUrl();

        let options = new RequestOptions({ headers: this.headers });
        options.url = url;
        options.method = this.method;
        options.body = params;
        return this.http.request(url, options).toPromise()
            .then((response: any) => this.extractData(response))
            .catch((error: any) => this.handleError(error));
    }
    //complete the other functions
}

weather.service.ts

@Injectable()
export class DashboardService extends BaseHttpService {
    constructor(private _http: Http) {
        super(_http);
    }

    getWeatherReport(params:any) {
        this.serviceUrl = 'some-url';
        this.method = "GET";
        return super.call(params);
    }
}

因此您可以注入 weather.service.ts 并覆盖 weather.service.ts 中的值并进行 http 调用

所以baseHttp.service.ts作为一个拦截器,所以你可以在那里拦截所有的Http调用。

Manish 的回答完全相同,但是当我们在 Angular 2 开始这个项目时,这个博客很有帮助。通过 http 网关的升级已经发生了巨大变化,当 angular 更改 4 中的 httpclient 时它非常有用。

https://blog.sstorie.com/adapting-ben-nadels-apigateway-to-pure-typescript

此外,如果您正在寻找放置基础 url 等的地方,我会在 angular-cli 中使用环境 ts 文件 https://github.com/angular/angular-cli/wiki/stories-application-environments