Max*_*x K 17 typescript angular2-services angular2-injection angular2-components angular
我想创建服务,它可以与一个组件进行交互.我的应用程序中的所有其他组件应该能够调用此服务,并且此服务应该与此组件交互.
如何从服务中调用组件方法?
@Component({
selector:'component'
})
export class Component{
function2(){
// How call it?
}
}
Run Code Online (Sandbox Code Playgroud)
从这个服务?
@Injectable()
export class Service {
callComponentsMethod() {
//From this place?;
}
}
Run Code Online (Sandbox Code Playgroud)
Tud*_*los 23
使用服务确实可以实现组件之间的交互.您需要将用于组件间通信的服务用途注入需要使用它的所有组件(所有调用程序组件和被调用方法)并使用Observables的属性.
共享服务可能如下所示:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CommunicationService {
// Observable string sources
private componentMethodCallSource = new Subject<any>();
// Observable string streams
componentMethodCalled$ = this.componentMethodCallSource.asObservable();
// Service message commands
callComponentMethod() {
this.componentMethodCallSource.next();
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个基本示例,其中单击Component1中的按钮将从Component2调用方法.
如果您想了解有关该主题的更多信息,请参阅专用文档部分:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
can*_*bax 12
该问题不要求组件交互,它要求从服务调用组件方法。
这可以通过向组件注入服务来实现。然后在服务内部定义一个方法,该方法将函数作为参数。该方法应该将此函数保存为服务的属性,并在任何需要的地方调用它。
// -------------------------------------------------------------------------------------
// codes for component
import { JustAService} from '../justAService.service';
@Component({
selector: 'app-cute-little',
templateUrl: './cute-little.component.html',
styleUrls: ['./cute-little.component.css']
})
export class CuteLittleComponent implements OnInit {
s: JustAService;
a: number = 10;
constructor(theService: JustAService) {
this.s = theService;
}
ngOnInit() {
this.s.onSomethingHappended(this.doThis.bind(this));
}
doThis() {
this.a++;
console.log('yuppiiiii, ', this.a);
}
}
// -------------------------------------------------------------------------------------
// codes for service
@Injectable({
providedIn: 'root'
})
export class JustAService {
private myFunc: () => void;
onSomethingHappended(fn: () => void) {
this.myFunc = fn;
// from now on, call myFunc wherever you want inside this service
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24591 次 |
| 最近记录: |