I have the following service imported in my component and somehow it is always null.
This is my appModule:
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TodayComponent } from './components/today/today.component';
import { WeekComponent } from './components/week/week.component';
@NgModule({
declarations: [
AppComponent,
TodayComponent,
WeekComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
My service
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class TodayService {
constructor(private http: HttpClient) { }
public today(object?): Observable<any> {
return this.http.get(`https://api.openweathermap.org/data/2.5/weather`, { params: object });
}
}
Component where I use it:
import { TodayService } from '../../services/today.service';
constructor(
public todayService: TodayService,
@Inject(DOCUMENT) private document: Document) {
}
public SUB_today: Subscription;
public success(pos: any) {
var crd = pos.coords;
this.SUB_today = this.todayService.today({lat: crd.latitude, lon: crd.longitude, appid: '**************'}).subscribe((res)=>{
this.today = res;
this.playingWithBG();
})
}
Everything seems correct and I don't get any errors in the compiler, however whenever I run the code I get:
ERROR TypeError: Cannot read properties of null (reading 'todayService')
Directly linking error with following part of the code: this.SUB_today = this.todayService.today
CodePudding user response:
The error actually says that this
is null
. So here: this.todayService
, you are trying to read null.todayService
.
How is that possible that this
is null
? Because of the way you call the function success
(as detailed in the question comments)
navigator.geolocation.getCurrentPosition(this.success, this.error);
You can either bind this
explicitly :
navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this));
or provide a lambda :
navigator.geolocation.getCurrentPosition(() => this.success(), () => this.error());
CodePudding user response:
Try to inject in the constructor an object of todaySErvice actually it is null cuz u dont use it.