我有一个如下的功能组件:
export class ChildComp {
whoAmI() {
return 'I am a child!!';
}
}
我的父组件:
import { ChildComp } form './child.component';
export class ParentComp {
constructor(private child: childComp ) {}
triggerChildFunction() {
this.childComp.whoAmI();
}
}
上面的方法对我不起作用。有人能建议我帮忙吗?
我想这就是"服务"概念的目的。
我的服务。服务。ts
@Injectable()
export class MyService<T> {
public stream$ = new Subject<T>();
public getSteam$() {
return this.stream$;
}
public publish(value: T) {
this.stream$.next(value);
}
}
子组件.ts
@Component()
export class ChildComponent<T> implements OnInit, OnDestroy {
public whoami = 'child';
private subscription: Subscription;
constructor(
private myService: MyService
) {}
public ngOnInit() {
this.subscription = this.myService.getStream$()
.subscribe((value: T) => {
this.functionToTrigger(value);
});
}
public ngOnDestroy() {
if(this.subscription) this.subscription.unsubscribe();
}
private functionToTrigger(arg: T) {
// do your stuff
console.log(JSON.stringify(arg))
}
}
父组件.ts
@Component()
export class ParentComponent<T> {
public whoami = 'parent';
constructor(
private myService: MyService<T>
) {}
public notifiyChild(value: T) {
this.myService.publish(value);
}
}
我认为,您的孩子应该是Angular服务,而不仅仅是类。
Injectable()
export class ChildService { // remember add this to module
public whoAmI() {
return 'I am a child!!';
}
}
import { ChildService } form './child.service';
export class ParentComp {
constructor(private child: childService ) {}
triggerChildFunction() {
this.childService.whoAmI();
}
}
您还可以使用Subject((或使用@ViewChild((来通信两个Angular组件。有关@ViewChild的更多信息,您可以在这里找到