I'm attempting to use Angular's HttpClient
in a service, but during runtime I'm encountering the following error:
ERROR TypeError: "this.http is undefined"
I'm importing HttpClientModule in my app.module.ts:
import { HttpClientModule } from '@angular/common/http';
...
@NgModule({
imports: [
HttpClientModule
...
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
...and importing HttpClient in my app.service.ts:
import { HttpClient } from '@angular/common/http';
import DataSource from 'devextreme/data/data_source';
...
@Injectable()
export class Service {
constructor(private http: HttpClient) {}
getDataSource(): DataSource {
return new DataSource({
byKey: function (key) {
return this.http.get("https://localhost/foobar" + encodeURIComponent(key))
}
});
}
}
Does this
refer to a different scope because it's in a new object? Do I need to pass http
in somehow, or does dependency injection cover that?
Try using arrow function to make sure that your this context refers to the current class instance:
Before:
byKey: function (key) {
After:
byKey: key => {