I am getting a " Uncaught TypeError: Cannot read property 'get' of undefined "

I am getting a " Uncaught TypeError: Cannot read property 'get' of undefined "

我正在尝试使用不同的端口从另一个微服务(本地)检索 json。我不确定问题出在我的配置还是微服务上。当我点击 url 时,我确实让 json 显示在页面上。

this.http.get('http://localhost:8081/*****', { responseType: 'json' }).subscribe(data => console.log(data));

***** = 检索 json

的页面

我期待 json 但是我收到一条错误消息。

你应该是这样的:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class TestService {

  constructor(private httpClient: HttpClient) { }

  public getData(): Observable<any> {
    const apiURL = `http://localhost:8081/*****`;
    const opts = {
       responseType: 'json'
    };

   return this.httpClient.post(apiURL, opts);
  }
}

来自您的组件:

import { TestService} from '..test.service';

export class TestClass {

  constructor(private testService: TestService) { }

  getInfo() {
   this.testService.getData().subscribe(data => {
     console.log('***TEST***' + data);
   }); 
  }
 }

对于遇到相同问题的任何人,我发现了我的错误。另一个微服务上的控制器在 RequestMapping 之前缺少 @CrossOrigin。这修复了我在进行调用的前端的错误。

@CrossOrigin
    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }