我想从在 router-outlet 内呈现的子组件进行导航。 我的父组件有一个路由器配置,我想在某些事件上手动导航。但是我不知道如何在没有输出的情况下将一些数据(用于导航)从 child 传递给 parent 。因为这个结构不工作
<router-outlet (navigateTo)="navigateToMessagePart($event)"></router-outlet>
我怎样才能以正确的方式做到这一点?也许从 child 那里导航?但是我如何从 child 那里得到父方法。 非常感谢您的帮助!
最佳答案
<router-outlet></router-outlet>
不能用于从子组件发出事件。在两个组件之间进行通信的一种方法是使用公共(public)服务。
创建服务
shared-service.ts
import { Observable } from "rxjs/Observable";
import { Injectable } from "@angular/core";
import { Subject } from "rxjs/Subject";
@Injectable()
export class SharedService {
// Observable string sources
private emitChangeSource = new Subject<any>();
// Observable string streams
changeEmitted$ = this.emitChangeSource.asObservable();
// Service message commands
emitChange(change: any) {
this.emitChangeSource.next(change);
}
}
现在在父组件和子组件的构造函数中注入(inject)上述服务的实例。
每次调用 onClick() 方法时,子组件都会发出变化
child.component.ts
import { Component } from "@angular/core";
@Component({
templateUrl: "child.html",
styleUrls: ["child.scss"]
})
export class ChildComponent {
constructor(private _sharedService: SharedService) {}
onClick() {
this._sharedService.emitChange("Data from child");
}
}
父组件应接收该更改。为此,在父级的构造函数中捕获订阅。
parent.component.ts
import { Component } from "@angular/core";
@Component({
templateUrl: "parent.html",
styleUrls: ["parent.scss"]
})
export class ParentComponent {
constructor(private _sharedService: SharedService) {
_sharedService.changeEmitted$.subscribe(text => {
console.log(text);
});
}
}
关于binding - 路由器导出的 Angular 2 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37662456/