我有 2 个子组件,我想将执行服务调用的一个子组件的错误数据传递给另一个子组件。限制是在这种情况下我不能使用 router
。
孩子 1
this.avafService.SubmitAVAFLoanAdjustment(this.submitAVAFLoanAdjustmentRequest).subscribe((resp)=>{
//success
}, error => {
console.log(error);
//set error value to model
})
孩子 2
ngOnInit(): void {
//get error here
//import model in Child 2 component and get model data
}
服务
型号
export interface ErrorDetail {
isError: boolean
statusNumber: number
statusHeaderCode: string
errorDescription: string
errorDescriptionKey: string
errorDescriptionIcon: string
errorList: ResultMessage[]
}
我还能做些什么来传递数据?我有一个正在尝试使用的服务和模型文件,但我不确定接下来要做什么。我添加了我正在尝试的评论。
答案 0 :(得分:1)
我过去是如何达到同样的结果的 首先创建服务myservice.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ErrorRportService {
errorReport = new Subject<any>();
constructor() { }
}
来自你孩子1
constructor(private errorReport:ErrorRportService) { }
this.avafService.SubmitAVAFLoanAdjustment(this.submitAVAFLoanAdjustmentRequest).subscribe((resp)=>{
//success
}, error => {
console.log(error);
this.errorReport.next(error);
//set error value to model
})
然后在您的孩子中订阅它 2
constructor(private errorReport:ErrorRportService) { }
ngOnInit(): void {
//get error here
//import model in Child 2 component and get model data
this.errorReport.errorReport.subscribe((data) => console.log(data));
}
答案 1 :(得分:1)
所以你可以通过使用一个基本上是可观察的主题来做到这一点:
服务文件
import { Subject } from 'rxjs';
errorSubject = new Subject<any>(); // any can be replaced by the error resp JSON Type
在子组件 1 中:
import {ServiceFileClassName} from './path';
.
.
.
constructor(private service: ServiceFileClassName){}
this.avafService.SubmitAVAFLoanAdjustment(this.submitAVAFLoanAdjustmentRequest).subscribe((resp)=>{
//success
}, error => {
console.log(error);
this.service.errorSubject.next(error) // pass the error response in the subject
})
在子组件 2 中:
import {Subscription } from 'rxjs';
import {ServiceFileClassName} from './path';
.
.
.
constructor(private service: ServiceFileClassName){}
subs:Subscription;
this.subs= this.service.errorSubject.subscribe((resp=>{
//use the error response that you get
})
.
.
.
ngOnDestroy(){
this.subs.unsubscribe()
}
另外,在 child2 组件中实现 onDestroy 并取消订阅主题的订阅。
答案 2 :(得分:0)
您可以使用事件发射器,或者更好的解决方案是在服务内部创建一个 Observable,让服务而不是组件触发错误,然后在组件内部订阅它。
答案 3 :(得分:0)
也许您可以尝试以下方法:
在 Child2
组件打字稿中,您必须创建一个方法来接收 error
变量的值,如下所示:
export class Child2Component {
constructor() { }
error:string;
receiveStringValue($event) {
this.error= $event
}
}
在 Child2
组件 html 中输入以下内容:
<app-child1 (stringValueEvent)="receiveStringValue($event)"></app-child1>
<h1>{{error}}<h1>
在 Child1
组件打字稿(app-child1 选择器)中,您应该使用 @Output()
装饰器声明一个 stringValueEvent 变量,并将其设置为一个新的事件发射器。
export class Child1Component {
error:string = "This is a demo error message";
@Output() stringValueEvent = new EventEmitter<string>();
constructor() { }
ngOnInit(): void {
this.stringValueEvent.emit(this.error)
}
}