在引导Angular2应用程序之前发出AJAX请求 [英] Make AJAX request before bootstrapping Angular2 application
问题描述
在我的Angular2应用程序中,我需要根据此调用的结果从AuthenticationService和bootstrap应用程序中调用某个函数.问题是AuthenticationService依赖于@ angular/http上的HTTP,而我对如何在调用引导程序功能之前手动构建http服务一无所知.此问题的已接受答案 angular2引导程序包含来自ajax调用的数据描述了我想要完美实现的目标,但不幸的是,它已提供给Angular2的某些早期版本.
In my Angular2 application I need to make a call to some function from AuthenticationService and bootstrap application based on results of this call. The problem is that AuthenticationService has dependency on HTTP from @angular/http and I have very little idea of how to build http service manually before calling bootstrap function. Accepted answer in this question angular2 bootstrap with data from ajax call(s) describes what I want to achieve perfectly, but unfortunately it was given to some previous version of Angular2.
我试图通过这种方式创建http服务:
I tried to create http service this way:
let injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS)
let http = injector.get(Http);
但是我在XsrfCookieStrategy或类似的东西中得到了空引用异常.我相信可以注入一些空的XsrfStrategy,但它似乎更像是一种技巧,而不是一个好的解决方案.所以问题是:有没有什么好的(正式的)方式来引导Angular2应用程序,并且提供一些类似于我上面添加的链接的依赖关系.
but I got null reference exception in XsrfCookieStrategy or something like that. I believe it is possible to inject some empty XsrfStrategy, but it seems to be more like a hack than a good solution. So the question is: are there any good (official) way to bootstrap Angular2 application with providing some dependencies up-front similar to the link I added above.
推荐答案
class AuthService {
isLoggedIn:BehaviorSubject<boolean> = BehaviorSubject<boolean>(false);
checkLogin(http:Http) {
return http.get(...)
.map(result => result.json())
.do(result => this.isLoggedIn.next(result)
}
}
bootstrap(AppComponent, [
HTTP_PROVIDERS,
AuthService,
{ provide: APP_INITIALIZER,
useFactory: (authService:AuthService) => authService.checkLogin(),
deps: [AuthService],
multi: true
}
]);
另请参见如何将从后端渲染的参数传递给angular2引导程序方法
这篇关于在引导Angular2应用程序之前发出AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!