Javascript 在组件之间传递数据时容易混淆
我是angular 6的新手,我正在使用angular 6创建项目。在分享数据时,我开始讨论这个问题 这是我的密码: 1) 组件侧栏:Javascript 在组件之间传递数据时容易混淆,javascript,angular,angular6,Javascript,Angular,Angular6,我是angular 6的新手,我正在使用angular 6创建项目。在分享数据时,我开始讨论这个问题 这是我的密码: 1) 组件侧栏: selectedCategory(type:any) { this.loginService.categoryType = type; // need to pass this data } 2) 列表组件: export class ListPostsComponent implements OnInit { ngOnInit() {
selectedCategory(type:any) {
this.loginService.categoryType = type; // need to pass this data
}
2) 列表组件:
export class ListPostsComponent implements OnInit {
ngOnInit() {
// here I need the data
}
}
3) 服务:
在您的服务中,当您需要将数据传递给另一个组件时,请将
categoryType
aSubject
,并调用next()
:
@Injectable({
providedIn: 'root',
})
export class LoginService {
private categoryType: Subject<any> = new Subject<any>();
public categoryType$ = this.categoryType.asObservable();
public sendData(data: any){
this.categoryType.next(data);
}
}
由于主体
既是观察者又是可观察者,因此您可以订阅该主体并监听您希望接收数据的组件中的更改:
export class ListPostsComponent implements OnInit {
constructor(private loginService: LoginService ){ }
ngOnInit() {
this.loginService.categoryType$.subscribe((data) => {
//use your data here
});
}
}
下面是Stackblitz中上述解决方案的一个工作示例:获取错误this.loginService.subscribe((数据)=>{//在此处使用数据})@Karan您是否从“rxjs”添加了import
import{Subject}代码>?属性“categoryType”是私有的,只能在类“LoginService”中访问。不起作用…问题在于侧栏和主组件同时加载,单击侧栏中的按钮后主组件如何重新利用component@Karan这看起来和你在问题中提到的不同,我的问题是,您是否能够从ListPostsComponent
组件获取数据?
constructor(private loginService: LoginService ){ }
selectedCategory(type:any) {
this.loginService.sendData(type);
}
export class ListPostsComponent implements OnInit {
constructor(private loginService: LoginService ){ }
ngOnInit() {
this.loginService.categoryType$.subscribe((data) => {
//use your data here
});
}
}