角度版本:12.0.1
我已经为一个组件创建了一个服务,我的要求是暂时仅将该服务与该组件一起使用。当我将服务注入组件并尝试访问其实例时,它是未定义的。第一次在 ngOnInit 中,它是可以访问的,但在其他地方未定义。
组件中相关代码:
@Component({
selector: 'app-component',
templateUrl: './app-component.component.html',
styleUrls: ['./app-component.component.scss'],
providers : [MyService]
})
export class AppComponent implements OnInit {
...some declarations and initializations
constructor(private myService: MyService) {}
ngOnInit(): void {
this.myObservable$ = this.myService?.getSomething('/');
}
functionCalledFromTemplaceButtonClick(item : any){
// The service is undefined here
return this.myService.getSomething(item);
}
}
服务相关代码:
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(
private httpClient: HttpClient,
) {}
getSomething(item: any) {
// Makes an api call here
}
}
我也在模块中提供了服务 - MyService。
现有问题均无济于事,请请求帮助。
我删除了我拥有的方法,并将其替换为箭头函数,并在顶部声明和定义,如下所示:
public functionCalledFromTemplaceButtonClick =(item : any) =>{
// The service has the context here
return this.myService.getSomething(item);
}