我有一个父组件,里面有一个路由器插座。在路由器插座中,我有一个组件,用于创建与父组件相关的新对象。能否请您帮助我了解如何与父组件沟通,他必须进行新的api调用以获取最新数据?
我正在考虑创建一个将具有rebuild = new BehaviourSubject(false)的服务,如果值更改为true,则父级应该监听它并发出新请求。你能帮我理解我应该如何解决这个问题吗?
答案 0 :(得分:0)
这样的事情应该让你开始
<强> parent.component.ts 强>
import { Component } from '@angular/core';
import { CommunicationService } from './communication.service';
@Component({
selector: 'my-app',
template: `<router-outlet></router-outlet>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private communication: CommunicationService) { }
ngOnInit() {
this.communication.tell$.subscribe((msg) => {
// call an api here
console.log(msg);
});
}
}
<强> child.component.ts 强>
import { Component, Input } from '@angular/core';
import { CommunicationService } from './communication.service';
@Component({
selector: 'hello',
template: `
<button (click)="communication.tell('hello')">
Tell parent
</button>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent {
constructor(public communication: CommunicationService) { }
}
<强> communication.service.ts 强>
import { Subject } from 'rxjs/Subject';
import { Injectable } from '@angular/core';
@Injectable()
export class CommunicationService {
private tellSource = new Subject();
tell$ = this.tellSource.asObservable();
tell(msg: string) {
this.tellSource.next(msg);
}
}
路由配置
const routes = [
{ path: '', component: ChildComponent },
]