当前将数据传递给路由的角度方法是将其添加到路由中。
例如,在官方Angular文档上的英雄指南之旅中,使用路由hero/:id将id传递到英雄组件。
不使用服务作为中介,或者使用诸如本地存储之类的东西来临时保存某些数据,在这种情况下,id是否可以传递id
发布于 2018-07-18 00:51:56
可以通过observable发送信息
service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class LoadDataService {
private setdataEmmit = new BehaviorSubject('initial info');
public getdataEmmit$ = this.setdataEmmit.asObservable();
constructor() { }
sendData(data: any) {
this.setdataEmmit.next(data)
}
}component1.ts
import { LoadDataService } from '.....';
@Component({
selector: 'app-1',
templateUrl:'',
styleUrls: ['']
})
export class Component1 implements OnInit {
constructor(
private _loadDataService: LoadDataService
) {
}
ngOnInit() {
this._loadDataService.sendData('info send');
}
}component2.ts
import { LoadDataService } from '.....';
@Component({
selector: 'app-2',
templateUrl:'',
styleUrls: ['']
})
export class Component2 implements OnInit {
constructor(
private _loadDataService: LoadDataService
) {
}
ngOnInit() {
this._loadDataService.getdataEmmit$.subscribe(
(data) => {
console.log(data);
// print: 'info send'
// YOU ALREADY HAVE THE DATA YOU SENT FROM THE COMPONENT 1
});
}
}https://stackoverflow.com/questions/48796772
复制相似问题