导入的服务始终为null



我在组件中导入了以下服务,但不知怎么的,它总是空的。

这是我的应用程序模块:

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 { }

我的服务

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 });
}
}

我使用它的组件:

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();
})
}

一切似乎都是正确的,我在编译器中没有任何错误,但每当我运行代码时,我都会得到:

ERROR TypeError: Cannot read properties of null (reading 'todayService')

直接将错误和代码的以下部分联系起来:this。SUB_today=this.todayService.today

错误实际上表明thisnull。所以这里:this.todayService,您正在尝试读取null.todayService

this怎么可能是null?由于您调用函数success的方式(如问题注释中所述(

navigator.geolocation.getCurrentPosition(this.success, this.error);

您可以显式绑定this

navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this));

或者提供λ:

navigator.geolocation.getCurrentPosition(() => this.success(), () => this.error());

尝试在构造函数中注入一个today的对象。否则,实际上它是空的,因为你不使用它。

最新更新