【发布时间】:2016-07-06 19:54:16
【问题描述】:
对于注释,我对 Angular 非常陌生(1 或 2 就这点而言)。
我正在尝试编写 Http 的“超级”层,以避免必须将相同的标头放在任何地方。
import {Http, ConnectionBackend, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs';
import {LoadingService} from "../../services/loading.service";
export class HttpLoading extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,
private _ls: LoadingService )
{
super(backend, defaultOptions);
}
getPostPutHeader() {
var authHeader = new Headers();
authHeader.append("Authorization", "Bearer "+ localStorage.getItem('token') );
authHeader.append('Content-Type', 'application/json');
return authHeader;
}
post(url: string, data:any):Observable<Response> {
this._ls.isLoading = true; // Exception here: this._ls is undefined
return super.post(url, data, { headers: this.getPostPutHeader() })
.map(res => {
this._ls.isLoading = false;
return res;
});
}
}
还有一个服务来判断请求何时执行;它被注入到上面的类 HttpLoading 中。
import {Injectable} from '@angular/core';
@Injectable()
export class LoadingService {
isLoading: boolean = false;
}
我的引导程序中有很多东西,包括 HttpLoading、LoadingService 和 ConnectionBackend(对于最后一个,如果它不在这里,我会得到一个异常)。
bootstrap(AppComponent, [
ConnectionBackend,
HttpLoading,
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
LoadingService,
disableDeprecatedForms(),
provideForms()
])
问题是我第一次调用HttpLoading 的post 方法(在另一个服务中),我在this._ls.isLoading 得到一个异常,因为this._ls 是未定义的,我想不通为什么。
如果您需要更多信息,请告诉我。
编辑
LoadingService 已正确注入到我的AppComponent(主要组件)中。
//imports
//@Component
export class AppComponent {
requesting:boolean = false;
constructor(public authService: AuthService, private router: Router, private _ls: LoadingService) {
}
navigate(route:string) {
this._ls.isLoading = true;
this.router.navigate([route])
.then(() => this._ls.isLoading = false);
}
}
可能的解决方案
看来您的公共/私有参数必须放在列表的首位。不过,我会让比我更熟练的人解释原因……
export class HttpLoading extends Http {
constructor(private _ls: LoadingService, backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
【问题讨论】:
标签: angularjs angular angular2-injection