首页 > 解决方案 > 我收到“未捕获的类型错误:无法读取未定义的属性 'get'”

问题描述

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

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

*****= 获取 json 的页面

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

标签: jsonangularangular-httpclient

解决方案


你应该有这样的东西:

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

推荐阅读