在AngularJS的“美好时光”中,我对按钮和链接有很好的指令,向我展示了在HTTP请求期间的负载微调器。
现在,我现在尝试使用Angular 7重建它,但是遇到了问题。希望有人能帮忙...
起初,我有一个漂亮的简单httpInterceptor在http请求开始和停止时发出事件:
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/finally';
import { LoadingService } from './loading.service';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(private loadingService: LoadingService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loadingService.onNotify(true)
return next.handle(request)
.finally(() => {
this.loadingService.onNotify(false)
});
}
}
到目前为止,这是可行的。现在,我创建了一个服务来处理事件:
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Injectable()
export class LoadingService {
// notify: Subject<boolean> = new Subject<boolean>();
notify: BehaviorSubject<boolean> = new BehaviorSubject(false);
onNotify(event) {
this.notify.next(true);
}
}
...最后是我的指令:
import { OnInit, Directive, ElementRef, Renderer2 } from '@angular/core';
import { LoadingService } from './loading.service';
@Directive({
selector: '[loading]'
})
export class LoadingDirective {
constructor(
private element: ElementRef,
private renderer: Renderer2,
private loadingService: LoadingService
) {
console.log("DIRECTIVE LOADING")
this.renderer.addClass(this.element.nativeElement, "required");
this.loadingService.notify.subscribe((result) => {
console.log('result', result)
})
}
}
问题是:它将无法工作!它已成功编译,但是尝试显示使用[loading]标签的组件时,出现控制台错误:
ERROR Error: "[object Object]"
resolvePromise http://localhost:4200/polyfills.js:3159:31
resolvePromise http://localhost:4200/polyfills.js:3116:17
scheduleResolveOrReject http://localhost:4200/polyfills.js:3218:17
invokeTask http://localhost:4200/polyfills.js:2766:17
...
为什么诺言无法兑现?我的错误在哪里?我真的希望你们中的某人能解决我的问题。