Angular 5 - 类型 '() => Observable<any>' 上不存在属性 'subscribe'

Mar*_*man 2 angular

我只是在编写一个简单的 Angular 实验,但出现以下错误……Property 'subscribe' does not exist on type '() => Observable<any>'我正在尝试通过服务将数据文件中的静态 json 数据加载到组件中。我不确定为什么会发生这种情况,因为我之前已经做过很多次了,这是我的 Angular 服务...

@Injectable({
    providedIn: 'root'
})
export class DashboardService {

    constructor(private http: HttpClient) {
   }

    public getDashboardData(): Observable<any> {
        return this.http.get('../../data/dashboard-data.json');
    }
}
Run Code Online (Sandbox Code Playgroud)

没什么奇怪的……现在让我们看看我的组件

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor(private dashboardService: DashboardService) { }

  ngOnInit() {
    this.dashboardService.getDashboardData.subscribe((result) => {
      console.log(result);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我看不出有什么问题?我以前已经这样做过很多次了。静态文件中的 JSON 是有效的并且是 linted。我一定错过了一些非常简单的东西,但我无法理解或看到我做错了什么。任何建议表示赞赏。

Saj*_*ran 6

getDashboardData() 是函数而不是变量,您需要将其更改为,

   this.dashboardService.getDashboardData().subscribe((result) => {
          console.log(result);
    });
Run Code Online (Sandbox Code Playgroud)

  • 天啊!Facepalm 时刻……真是漫长的一天! (4认同)