gpt4 book ai didi

订阅回调中的 javascript 错误

转载 作者:行者123 更新时间:2023-12-03 01:00:06 26 4
gpt4 key购买 nike

  • 我有一个组件 A,在我的用例中,我使用 behaviourSubject 将数据广播到组件 B,每次点击组件一中的按钮时,都会在组件 B 中触发 http 请求。
  • 在组件 B 中,我正在订阅组件 A 广播的可观察对象。

组件A:

import { Component, OnInit } from '@angular/core';
import { MessagingService } from '../messaging.service';

@Component({
selector: 'app-comp-a',
templateUrl: './comp-a.component.html',
styleUrls: ['./comp-a.component.css']
})
export class CompAComponent implements OnInit {

public i= 0;

constructor(public message: MessagingService) { }

ngOnInit() {

}

broadcast(){
this.message.broadcast({data:`Broadcasted_${this.i}`});
this.i++
}

}

组件B:

import { Component, OnInit } from '@angular/core';
import { MessagingService } from '../messaging.service';
import { switchMap } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
selector: 'app-comp-b',
templateUrl: './comp-b.component.html',
styleUrls: ['./comp-b.component.css']
})
export class CompBComponent implements OnInit {
public data;
constructor(public message: MessagingService) {}

ngOnInit() {
this.message.getData().pipe(
switchMap(res => {
/**
* here some service call based on brodcasted data.
*
* Lets say service returns json in format
* {
* data:[{},{}]
* }
*/
return of([res.data]);
})
).subscribe(res => {
/**
* So in actual use case I will get
* {
* data:[{},{}]
* }
* in subscription.
*
* now lets assume sometime I get data as null and i tried to access it as res.data[0].some_property
then it will throw js error Cannot read property '0' of undefined so subscription breaks and doesnt complete and stops. and then after subsequent broadcast from comp A doesnt triggers subscription in comp B.. is it expected behaviour?
*/

// let a = this.data[0] //this is delibrate error to simulate my realtime issue
this.data = res
}, (error) => {
console.log("Error happened" + error)
}, () => {
console.log("the subscription is completed")
})
}

}

服务:

import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Injectable()
export class MessagingService {

/**
* Subject to notify the offer console
*/

private _change_in_year_month = new BehaviorSubject<any>({ data:'old data' });
public change_in_year_month = this._change_in_year_month.asObservable();

constructor() { }

/**
*
* @param data data contains either year or (year and month)
* This method will broadcast data to offer console to execute service call
*/
broadcast(data) {
this._change_in_year_month.next(data);
}

/**
* Method will return observable of Subject which can be subscribed in
* offer console component to execute service call
*/
getData() {
return this.change_in_year_month;
}

}

现在假设组件 B 中的订阅中发生了某种 js 错误(可能是无法读取未定义的属性“0”),然后我的进一步 JavaScript 执行停止并且不监听后续广播值。

这是 Rxjs 的预期行为吗?我该如何处理 subscribe block 中发生的 js 错误。

问题可以在 Stackblitz 处模拟。最初单击广播按钮,然后您可以看到正在显示的数据。现在取消注释第 38 行以模拟问题并单击广播。它永远不会监听后续调用。

最佳答案

如果 observable 死亡,它会调用它的错误处理程序,并且它们已关闭,您无法通过它们发送任何内容,这意味着它们已关闭,包括间隔在内的上游所有内容都已死亡。

what if we want to live.

屏蔽主观察者链是解决方案
将 catch 放入 switchmap每当触发请求时 switchmap创建 ajax observable,这次使用捕获
switchMap() 不关心内部 Observable 是否已完成,它仅在外部 Observable 完成时才会完成。即使内部 Observable 链死亡,外部 Observable 链仍保持事件状态,因为尚未为外部 Observable 链调用错误处理程序。
示例

switchMap((value)=>this.http.get('url' + value).pipe(catchError(() => {return empty()}))
))

<强> How to keep an Observable alive after Error in Angular?

关于订阅回调中的 javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52663484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com