【发布时间】:2018-08-14 23:01:55
【问题描述】:
在我的服务中,我创建了一个我将在另一个组件中使用的可观察对象
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
@Injectable()
export class ApiHandlerService {
modalObject = new Subject<any>();
constructor(
private router: Router,
private http: HttpClient,
) {}
responseHandler(response) {
if (response.success) {
const obj = {
exception: false,
payload: response.payload
};
this.modalObject.next(obj);
return obj;
} else {
const obj = {
exception: true,
message: response.exception.message,
segNum: response.exception.seqNum
};
this.modalObject.next(obj);
return obj;
}
}
errorHandler(err) {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.router.navigate(['/app-login']);
}
}
}
}
然后在我的组件中订阅 observable。
import { Component, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ApiHandlerService } from 'app/services/api-handler/api-handler.service';
@Component({
selector: 'app-api-handler-modal',
templateUrl: './api-handler-modal.component.html'
})
export class ApiHandlerModalComponent implements OnInit, OnDestroy {
@ViewChild('autoShownModal') autoShownModal: ModalDirective;
isModalShown = false;
subscription: Subscription;
constructor(
private apiHandlerService: ApiHandlerService
) {}
ngOnInit() {
this.subscription = this.apiHandlerService.modalObject.subscribe(obj => console.log(obj));
}
ngOnDestroy() {
// this.subscription.unsubscribe();
}
showModal(obj?): void {
this.isModalShown = true;
}
hideModal(): void {
this.autoShownModal.hide();
}
onHidden(): void {
this.isModalShown = false;
}
}
所以您可以看到,当我订阅时,我只是在尝试控制台记录订阅值。这似乎不起作用,我对可观察对象有点太陌生了,无法弄清楚出了什么问题?
【问题讨论】:
-
是否有任何事情导致服务的
responseHandler函数触发?除非有什么东西让Subject.next()运行,否则你不会看到太多事情发生。 -
响应处理程序在我所有使用 http.get/pull 的组件中被调用。我知道这部分正在工作,否则我将无法在组件模板中获取有效负载。
-
1.尝试在视图中消费从服务返回的值,这将确保从“当前组件”正确调用服务
-
@SandraWillford 你能解决这个问题吗?或者查询的任何更新?
-
@Nitin 我不得不搁置它,所以我没有取得任何新进展
标签: angular