我是Angular的新手,但遇到了问题。 我有一个简单的配置文件config.json
{
"param1": "https://localhost:44381/odata/"
}
我还有一个服务(HttpService),可以发出http请求。
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
@Injectable()
export class HttpService{
constructor(
private httpClient: HttpClient
) { }
// This code was taken from Angular guide
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return throwError('Something bad happened; please try again later.');
};
getData(url:string) {
return this.httpClient.get(url)
.pipe(
catchError(this.handleError)
);
}
}
还有ConfigService,其目的是读取配置文件。在这里,我使用我的HttpService。
import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import { Observable } from 'rxjs';
@Injectable()
export class ConfigService{
private readonly configUrl: string = 'assets/config.json';
constructor(
private httpService: HttpService
) { }
getConfig(): Observable<Object> {
return this.httpService.getData(this.configUrl);
}
getConfigParam(paramName: string): string {
let result: string = 'Initial value'; // value set for visualization only
//this.httpService.getData(this.configUrl)
this.getConfig()
.subscribe((data) => result = data[paramName],
error => this.error = error);
if (this.error)
return 'Some error happened'
return result;
}
}
在我的componenet中,我调用getConfig函数来呈现整个配置文件,一切正常。 然后,我尝试从配置中获取参数值,调用this.configService.getConfigParam('param1')函数,它不起作用。函数返回“初始值”。 如果我直接在组件中使用功能代码,它将起作用。
import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../config.service';
@Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.css']
})
export class ContactsComponent implements OnInit {
configData: string;
error;
paramValue: string;
constructor(private configService: ConfigService) { }
ngOnInit(): void {
// Here config file contents are written to configData variable
this.configService.getConfig()
.subscribe((data) => this.configData = JSON.stringify(data),
error => this.error = error);
// Here getConfigParam function returns undefined
this.paramValue = this.configService.getConfigParam('param1');
// Doing the same from component works
this.configService.getConfig()
.subscribe((data) => this.paramValue = data['param1'],
error => this.error = error);
}
}
似乎订阅在服务内部无效。无法理解是怎么回事。 谢谢!