【发布时间】:2021-07-15 02:54:24
【问题描述】:
大家好,第一次在这里提问。我希望它写得足够好:)
让我们直接解决问题。 我有一个关于 typescript 中的 behaviorSubject 变量的问题,该变量不允许我在调用后端 API (PHP) 后将数据存储在服务的数组中。下面是main函数的代码:
public notificationsGeneral: BehaviorSubject<TemplateNotificationModel[]> = new BehaviorSubject<TemplateNotificationModel[]> ([]);
public notificationsPublic: BehaviorSubject<TemplateNotificationModel[]> = new BehaviorSubject<TemplateNotificationModel[]> ([]);
public notificationsPrivate: BehaviorSubject<TemplateNotificationModel[]> = new BehaviorSubject<TemplateNotificationModel[]> ([]);
public notificationsAll: BehaviorSubject<TemplateNotificationModel[]> = new BehaviorSubject<TemplateNotificationModel[]> ([]);
public getUserNotifications(userId: number): void{
this.http.get<TemplateNotificationModel[]>(this.BACKEND_URL + 'notifications/user/' + userId).subscribe(
(data) => {
this.notificationsAll.next(data);
this.notificationsAll.subscribe(
data => {
this.sortNotifications(data);
}
)
},
(error) =>{
console.log(error);
}
);
console.log("2º " + this.notificationsPrivate.getValue())
/*
Result here is: 2º
*/
这里是 sortNotifications():
sortNotifications(data: any){
var gen = []
var pub = []
var priv = []
for(let element of data){
switch(element.notification_type.id){
case NotificationTypes.GENERAL:
gen.push(element);
break;
case NotificationTypes.PUBLIC:
pub.push(element);
break;
case NotificationTypes.PRIVATE:
priv.push(element);
break;
}
}
this.notificationsPublic.next(pub);
this.notificationsGeneral.next(gen);
this.notificationsPrivate.next(priv);
console.log("1º " + this.notificationsPrivate.getValue())
/*
Result here is
1º [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
*/
}
具有“1º”的 console.log 正在返回填充了我想要的数据的数组,但订阅之外的控制台日志(具有“2º”的控制台日志)正在返回空数组。
我不知道我是否遗漏了一些关于编码的基本知识,但我没有做任何可以擦除该数组中数据的操作。那么为什么会这样呢?
非常感谢!
警察局:
1- 我必须将数据存储到这些数组中,因为服务中有更多函数将读取该数据。
2- 我使用 behaviorSubject 是因为有些组件将订阅这些数组的 getters 函数,并且必须在更新时检测和更新更改。
【问题讨论】:
标签: html arrays typescript