小编Gam*_*ney的帖子

启动时后端的Angular2加载配置

在我的Angular2应用程序中,我正在尝试使用HTTP在引导程序中从后端加载配置,以便我可以使用提取的数据来创建角度服务.

每当我尝试读取保存在我的Config中的HTTP响应时,我总是得到TypeError:无法读取未定义错误的属性'url'.

看起来HTTP请求仅在整个引导程序方法完成时才完成,而我的代码尝试在检索之前提取Observable响应.

如何修复它以从服务器中提取配置并使用它在启动时创建角度服务?(我想在提取数据的提供者中创建服务)

如果在启动时有更好的方法从服务器中提取配置,请发表评论.

我的main.ts看起来像这样:

bootstrap(AppComponent, 
    [APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
    .catch(err => console.error(err)
);
Run Code Online (Sandbox Code Playgroud)

configuration.service.ts

@Injectable()
export class ConfigurationService {

    constructor(private http: Http) {
    }

    load() {
        return this.http.get('config/getConfig').map(response => response.json());
    }

}
Run Code Online (Sandbox Code Playgroud)

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts

@Component({
    selector: 'app',
    templateUrl: 'app/app.component.html',
    styleUrls: …
Run Code Online (Sandbox Code Playgroud)

angular2-services angular

14
推荐指数
2
解决办法
9138
查看次数

标签 统计

angular ×1

angular2-services ×1