【发布时间】:2016-07-11 06:05:03
【问题描述】:
在我的 Angular2 应用程序中,我正在尝试使用 HTTP 在引导程序上从后端加载配置,以便我可以使用提取的数据来创建角度服务。
每当我尝试读取保存在我的配置中的 HTTP 响应时,我总是得到 TypeError: Cannot read property 'url' of undefined 错误。
似乎只有在整个引导方法完成时 HTTP 请求才完成,而我的代码试图在检索到 Observable 响应之前提取它。
如何修复它以从服务器中提取配置并在启动时使用它来创建角度服务? (我想用提取的数据在提供者内部创建服务)
如果有更好的方法在启动时从服务器中提取配置,请发表评论。
我的 main.ts 看起来像这样:
bootstrap(AppComponent,
[APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
.catch(err => console.error(err)
);
configuration.service.ts
@Injectable()
export class ConfigurationService {
constructor(private http: Http) {
}
load() {
return this.http.get('config/getConfig').map(response => response.json());
}
}
config.ts
@Injectable()
export class Config {
public config;
constructor(public configurationService: ConfigurationService) {
configurationService.load().subscribe(
config => this.config = config,
error => console.error('Error: ' + error)
);
}
get(key: any) {
return this.config[key];
}
}
app.component.ts
@Component({
selector: 'app',
templateUrl: 'app/app.component.html',
styleUrls: ['app/app.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [MyService]
})
export class AppComponent {
constructor(public myService: MyService) {
}
}
my.service.ts
@Injectable()
export class MyService{
private url;
constructor(public config: Config) {
this.url = config.get('url');
}
}
【问题讨论】:
-
从错误中可以清楚地看到,再次查看您的
url,这是未定义的