我有2个组件,Profile&图像(两者都有不同的路线)。我想从Image组件中的Profile中访问一个变量。
我在 BusinessList 组件中有一个按钮,当用户点击该按钮时,它应该重定向到主页,我将一个项目添加到localstorage。
在主页配置文件中,图片和联系人位于不同的标签中。
在BusinessList中单击按钮后,将激活配置文件选项卡。在这里,我获取本地存储项,存储一个变量 - 我想从Image,contacts --- tabs
访问它的相同变量这是我的个人资料组件
import { Component, OnInit} from '@angular/core';
@Component({
moduleId: 'module.id',
selector: 'my-profile',
templateUrl: '../views/business.images.html',
})
export class BusinessProfileComponent {
public userAction: any;
constructor(private router: Router, activeroute: ActivatedRoute,
BusinessSettingService: BusinessSettingService) {
this.userAction = localStorage.getItem("action")
BusinessSettingService.userTakenAction.next(this.userAction);
console.log(this.userAction, ' this.userAction')
}
}
此处 userAction 是组件之间的可共享数据
图片组件
import { Component, OnInit} from '@angular/core';
@Component({
moduleId: 'module.id',
selector: 'my-core',
templateUrl: '../views/business.images.html',
})
export class BusinessImagesComponent{
constructor( private router: Router, BusinessSettingService: BusinessSettingService) {
BusinessSettingService.userTakenAction.subscribe(value => {this.userImageaction= !value;})
}
BusinessSettingService
import { Injectable,Output,EventEmitter } from '@angular/core';
@Injectable()
export class BusinessSettingService {
public userTakenAction: EventEmitter<string> = new EventEmitter<string>();
}
我使用EventEmitter
为组件创建了自定义服务,这是解决此方案的好方法,还是有更好的方法来实现这一点?
我无法在Image组件中获取userAction值。请帮我解决此问题
答案 0 :(得分:0)
将您的BusinessSettingService更新为以下一个:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class BusinessSettingService {
// Observable for selection source
private userActionSource = new Subject<any>();
// Observable for selection stream
userActionStream$ = this.userActionSource.asObservable();
userActionUpdated(userAction: any) {
console.log('user action is: ' + userAction);
this.userActionSource.next(userAction);
}
}
现在,在Profile和Image组件中,在构造函数中启动BusinessSettingService,只需订阅此观察者并更新值。
在组件构造函数中:
constructor (private businessSettingService: BusinessSettingService) {}
然后订阅它并更新值:
this.businessSettingService.userActionUpdated(this.userAction);
同样,在您的Image组件中,订阅此observable并使用以下代码获取更新的值。
this.businessSettingService.userActionStream$.subscribe(
value => {
this.userAction = value;
}
);
希望这有帮助。