首页 > 解决方案 > 如何从 http 中读取对象(基本上是 Json 数据),获取角度 6

问题描述

我是 Angular 的新手(所以这可能是愚蠢的怀疑)我正在构建一个服务,我可以从任何组件调用该函数并使用该服务函数以对象的形式为我提供 json 值。所以我从我的组件调用函数,然后尝试在控制台上打印我的值

这是app-component.ts文件

import { Component } from '@angular/core';
import { CallServiceService } from './call-service.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  message: string;
  obj;

  constructor(private callservice: CallServiceService, private http: HttpClient) {
    console.log("Here in component");
  }

  ngOnInit(): void {
    this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails');
    console.log(this.obj);
  }
}

我的服务文件是call-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable({
  providedIn: 'root'
})
export class CallServiceService {
  base_api_url: string = "http://localhost:5000/";
  process: string = "";
  constructor(private http: HttpClient) {
  }

  calledService(end_url: string) {
    return this.http
      .get(this.base_api_url + end_url)
      .catch(this.handleError)
      .subscribe(data => obj.successCallback(data));
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}

所以我需要读取组件文件中的值,但没有显示所需的输出

标签: angular

解决方案


订阅组件中的调用服务。

服务

calledService(end_url: string) {
    return this.http.get(this.base_api_url + end_url);
    // remove subscriber
}

零件

ngOnInit(): void {
    this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails')
        .subscribe(data => console.log(data));
    // Assign data to some variable and use in HTML
}

推荐阅读