对于注释,我对 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
'spost
方法(在另一个服务中)时,我在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);
}