angular - 无法使用角度订阅转移价值
问题描述
我正在使用主题和订阅在两个组件之间传输数据,但它对我不起作用。
// 第一个组件
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { SettingsHelperService } from '../settings-screen/settings-helper.service';
@Component({
selector: 'app-master-data-config',
templateUrl: './master-data-config.component.html',
styleUrls: ['./master-data-config.component.css']
})
export class MasterDataConfigComponent implements OnInit, OnDestroy {
zoneSelected: boolean = false;
wingSelected: boolean = false;
public subscription: Subscription;
constructor(private settingHelperService: SettingsHelperService) { }
public ngOnDestroy(): void {
this.subscription.unsubscribe(); // onDestroy cancels the subscribe request
}
ngOnInit(): void {
this.subscription = this.settingHelperService.getSelectedValue().subscribe(data => console.log(data));
}
}
// 第二个组件
import { Component, OnInit } from '@angular/core';
import { SettingsHelperService } from './settings-helper.service';
@Component({
selector: 'app-settings-screen',
templateUrl: './settings-screen.component.html',
styleUrls: ['./settings-screen.component.css']
})
export class SettingsScreenComponent implements OnInit {
public UnitType = [
{value: 'matric', viewValue: 'Matric'},
{value: 'imperial', viewValue: 'Imperial'},
];
zoneSelect: boolean = false;
wingSelect: boolean = false;
selectedUnitType: string;
valueSelected = [];
constructor(private settingHelperService: SettingsHelperService) { }
ngOnInit() {
}
save(){
let valueObj = {
unitType: this.selectedUnitType,
zoneSelect: this.zoneSelect,
wingSelect: this.wingSelect
}
this.settingHelperService.setValues(valueObj);
}
}
// 服务
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable()
export class SettingsHelperService {
public unitType:string;
public valueSubmitted = null;
public data = new Subject<any>();
constructor() { }
getSelectedValue(){
return this.data.asObservable();
}
setValues(value){
console.log(value);
this.data.next(value);
}
}
请建议我错在哪里..?
我没有检索组件中的更新值。
解决方案
除了您没有在提供 SettingHelperService 的位置显示代码外,我没有看到您的代码有任何明显的问题。那可能是个问题。如果没有正确提供,两个组件都可以拥有自己的服务实例并且不共享同一个。尝试在服务中添加此代码:
@Injectable({
providedIn: 'root',
})
如果那没有帮助,请检查我根据您的代码制作的 Stackblitz。添加上述内容后,它按原样工作:https ://angular-ivy-g8keel.stackblitz.io
推荐阅读
- python - 验证损失和验证准确率均高于训练损失,并且存在波动
- load-balancing - 通过生成 API Gateway 的多个副本来处理负载来扩展 API Gateway 是否可能/最佳实践?
- python - ValueError:无法将字符串转换为浮点数:“组件 A 到反应器”
- excel - 将工作表从一个 WB 移动到另一个新 WB
- jquery - Angular JS JQuery 模式未显示
- python - 比较数据框两行中的值,如果它们在另一列中具有相同的值
- c++ - 错误消息'预期; 在顶级声明符''未知类型名称导入'与框架添加包Futter之后
- javascript - Leaflet - openPopup() 不显示 geoJSON
- python - 从字典列表中提取新字典
- c# - 仅更新 Microsoft Dynamics 实体中的某些字段