我对将数据从子级传递到父级并路由到父级页面而不重新加载有疑问。
first.component.ts
@Component({
selector: 'app-first',
templateUrl: './first.component.html'
})
export class FirstComponent implements OnInit {
private test: any;
private data: any;
constructor(
private eventEmitterService: EventEmitterService
) { }
ngOnInit() {
if (this.eventEmitterService.subsVar==undefined) {
this.eventEmitterService.subsVar = this.eventEmitterService.
invokeFirstComponentFunction.subscribe((name:string) => {
this.firstFunction(name);
});
}
}
firstFunction(name: string) {
alert( 'Hello ' + '\nWelcome to C# Corner \nFunction in First Component');
}
first.component.html
<a routerLink="second">Second Component</a>
second.component.ts
@Component({
selector: 'app-second',
templateUrl: './second.component.html'
})
export class SecondComponent implements OnInit {
@Input() count: number;
@Output() countChange = new EventEmitter();
constructor(
private eventEmitterService: EventEmitterService, private router: Router) { }
ngOnInit() {
}
firstComponentFunction(name:string){
this.eventEmitterService.onFirstComponentButtonClick("Hello Data From Second Component");
}
}
second.component.html
<input type="button" value="Call First Component Function" (click)="firstComponentFunction($event)" routerLink="first">
event-emitter.service.ts
@Injectable({
providedIn: 'root'
})
export class EventEmitterService {
private data: any;
invokeFirstComponentFunction = new EventEmitter();
subsVar: Subscription;
constructor() { }
onFirstComponentButtonClick(data) {
this.invokeFirstComponentFunction.emit(data);
}
}
在这种情况下,当我添加事件发射器时,它可以完美地将数据传递到First组件,但是我想使用事件发出的数据路由到First页面,但又不想重新加载整个页面。在second.component.html中,我在事件发射器动作后使用routerLink,但它会清除事件发射的数据并再次加载页面。