我正在嘗試使用服務中的引數觸發組件方法。
假設我有組件
myComponent.ts
myMethod(myParameter: string){
...
}
如何使用服務中的自定義引數觸發該方法?我知道這不是最佳做法。
uj5u.com熱心網友回復:
您描述的方法顯然是“非 Angular”。服務不會呼叫組件上的方法。
正如您帖子的評論中提到的,實作您想要的行為(組件對服務更改做出反應)的“正確”方法是使用 Observable。
您的服務將公開某種形式的類似 Observable 的流(Observable、Subject、BehaviorSubject),并且組件將訂閱它以對其發射做出反應。
是的,它“更難”,但它是最佳實踐,也是實作您所尋找的唯一干凈方式。
uj5u.com熱心網友回復:
您可以使用rxjs 實作此目的。
您可以在組件中訂閱“主題” 。
您在服務中創建一個“主題”并在組件的 ngOninit 中訂閱它
在訂閱回呼中,呼叫組件的方法。
請看下面的模擬示例:
測驗服務.ts
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class TestService {
// subscribe to this in component
triggerMethod = new Subject<any>();
// this service method will trigger your component method
serviceMethod( myCustomParam: any): void {
this.triggerMethod.next(myCustomParam);
}
}
我的組件.ts
import { TestService } from 'test.service';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss'],
})
export class MyComponent implements OnInit {
constructor(private testService: TestService) {};
ngOninit() {
this.testService.triggerMethod.subscribe(myCustomParam => {
// call your method whenever its triggered.
this.myMethod(myCustomParam)
});
}
// your method
myMethod(myParameter: string){
...
}
}
確保在 ngDestroy 中取消訂閱它。 讓我知道是否有任何不清楚的地方。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437538.html
