【问题标题】:Angular: call function from other componentAngular:从其他组件调用函数
【发布时间】:2018-01-22 04:22:33
【问题描述】:
【问题讨论】:
标签:
javascript
angular
typescript
【解决方案1】:
那是因为你要调用它的函数的组件没有被实例化。
对于组件通信,您可以改用service:
服务
@Injectable()
export class MyService {
myCustomFunction(){
}
}
组件
在您的组件中:
@Component({
selector: 'my-component',
providers: [ MyService ]
})
export class MyComponent {
// inject your service to make it available
constructor(private service: MyService){}
doStuff(){
// call function which is located in your service
this.service.myCustomFunction();
}
}
【解决方案2】:
正如其他人所说,我更喜欢这些组件中带有Subject 的共享服务。
服务:
@Injectable()
export class SharedService {
mySubject = new Subject();
}
WorldComponent(订阅者):
export class WorldComponent {
constructor(private sharedService: SharedService){
this.sharedService.mySubject.subscribe((data)=>{
this.worldFunction();
})
}
HelloComponent(发布者):
public helloFunction() {
alert('Hello');
this.sharedService.mySubject.next(true);
}
您可以在此处找到更新后的示例:https://stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts
【解决方案3】:
错误的原因是 hello 组件没有被导入,而不是从另一个组件调用一个组件,你应该在两者之间使用一个服务,正如其他答案已经建议的那样。