您好我正在尝试使用事件发射器创建一个加载框组件,这是我到目前为止:
我创建了一个http.service thrrew,所有http调用都传递了:
@Injectable()
export class HttpService {
private http: Http;
@Output() ajaxStarted: EventEmitter<any> = new EventEmitter();
constructor(http: Http) {
this.http = http;
}
public get(url: string): Observable<Response> {
this.ajaxStarted.emit(url);
return this.http.get(url);
}
}
我使用以下代码创建了一个LoadingBoxComponent:
@Component({
selector: 'loading-box',
templateUrl: 'app/common/components/loading-box.view.html',
styleUrls: ['app/common/components/loading-box.style.css']
})
export class LoadingBoxComponent {
public isLoadingBoxHidden: boolean = true;
public showLoadingBox(event: any) {
this.isLoadingBoxHidden = false;
}
}
这是app / common / components / loading-box.view.html:
<div class="loading-box-container"
(ajaxStarted)="showLoadingBox($event)"
[ngClass]="{hidden: isLoadingBoxHidden }">
<div class="loading-box-shadow"></div>
<div class="loading-box-element">
<i class="fa fa-spinner fa-lg fa-spin"></i>
</div>
</div>
我不是在这里发帖我认为这与当前的问题无关。
我希望这里发生的是每当调用this.ajaxStarted.emit(url)时 我希望showLoadingBox函数可以从LoadingBoxComponent执行。
发生的事情是this.ajaxStarted.emit(url)被执行但是没有到达showLoadingBox。
我做错了什么?
答案 0 :(得分:2)
@Output() xxx:EventEmitter;
需要位于LoadingBoxComponent
而不是某些服务中。
@Injectable()
export class HttpService {
private http: Http;
ajaxStarted: EventEmitter<any> = new EventEmitter();
constructor(http: Http) {
this.http = http;
}
public get(url: string): Observable<Response> {
this.ajaxStarted.emit(url);
return this.http.get(url);
}
}
@Component({
selector: 'loading-box',
templateUrl: 'app/common/components/loading-box.view.html',
styleUrls: ['app/common/components/loading-box.style.css']
})
export class LoadingBoxComponent {
@Output() ajaxStarted: EventEmitter<any> = new EventEmitter();
constructor(http:HttpService) {
http.ajaxStarted.subscribe(this.ajaxStarted.edmit);
}
public isLoadingBoxHidden: boolean = true;
public showLoadingBox(event: any) {
this.isLoadingBoxHidden = false;
}
}