【问题标题】:Angular : How to receive API response in service fileAngular:如何在服务文件中接收 API 响应
【发布时间】:2018-03-31 06:06:32
【问题描述】:

我正在开发一个 Angular 应用程序,在这个应用程序中,我使用 HttpClient 模块来使用 API 响应。我开发了一些东西,但我总是得到“未定义”作为响应。

这里我有两个组件和一个服务文件,从 Landingpage.component.ts 我有 onclick 事件,它将“产品名称”传递给服务文件,从服务文件 (cartdata.service.ts) 我将产品名称传递给 API

API 将返回特定产品的图像路径。我在服务内接收 API 响应并对其进行处理,然后将数据传递给该组件的 mycart.component.ts 组件我正在为受尊重的 HTML 页面分配路径.

我想做的是,从 API 响应中获取特定产品的所有图像路径,并将其分配给受尊重的 HTML 页面。

landinpage.component.ts - cartdata.service.ts -my-cart.component.ts-HTMLpages API 响应:

这是我从 API 收到的响应。

This is my landingpage.components.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CartdataService } from '../../services/cartdata.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-landingpage',
  templateUrl: './landingpage.component.html',
  styleUrls: ['./landingpage.component.css']
})
export class LandingpageComponent {
  product_Name: any;
  ngOnInit() { }

  constructor(private CartdataService: CartdataService, private router: Router{}

  getProductName(Pname: any) {
    this.CartdataService.get_Product_Path(Pname.textContent);
  }
}

这是我的 cartdata.service.ts

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

@Injectable()
export class CartdataService {

  public i_product_Path = new BehaviorSubject<any>('');
  i_cast_Product_Path = this.i_product_Path.asObservable();

  public j_product_Path = new BehaviorSubject<any>('');
  j_cast_Product_Path = this.j_product_Path.asObservable();

  public k_product_Path = new BehaviorSubject<any>('');
  k_cast_Product_Path = this.k_product_Path.asObservable();

  public Count = new BehaviorSubject<number>(0);
  cast = this.Count.asObservable();

  currentCount :number = 0;
  current_product :any;
  i_COUNTER :number;
  j_COUNTER :number;
  k_COUNTER :number;

  big_Image_Path:string[][];
  small_Image_Path:string[][];
  selected_Product_Image: string[][];

  constructor(private http: HttpClient) { }

  editCount(newCount: number) {
    this.currentCount += newCount;
    this.Count.next(this.currentCount);
  }


  get_Product_Path(pName: string) {
    this.current_product = pName.trim();
    this.http.get(`http://localhost:abc/api/data/GetImage/?imageName=${this.current_product}`)
      .subscribe(data => {

        this.i_COUNTER = data[0].Count;
        this.j_COUNTER = data[1].Count;
        this.k_COUNTER = data[2].Count;

        if(this.i_COUNTER >0) {
          let i:number;
            for( i=0;i<=this.i_COUNTER;i++){
              this.big_Image_Path =data[0]['big_Images'];
            }
        }

        if(this.j_COUNTER >0){
          let j:number;
          for( j=0;j<=this.j_COUNTER;j++){
            this.small_Image_Path =data[1]['small_Images'];
          }
        }

        if(this.k_COUNTER >0){
          let k:number;
          for( k=0;k<=this.k_COUNTER;k++){
            this.selected_Product_Image =data[2]['selected_Product_Image']
          }
        }

        this.i_product_Path.next(this.big_Image_Path);
        this.j_product_Path.next(this.small_Image_Path);
        this.k_product_Path.next(this.selected_Product_Image);
      });
  }
}

这是我的 my-cart.component.ts

import { Component, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { CartdataService } from '../../services/cartdata.service';
import { Http } from '@angular/http';

@Component({
  selector: 'app-my-cart',
  templateUrl: './my-cart.component.html',
  styleUrls: ['./my-cart.component.css'],
  outputs: ['ChildEvent']
})

export class MyCartComponent {
nCount: number;
  product_Name: any;
  i_path: string[][];
  j_path: string[][];
  k_path: string[][];
  i_Counter :number;
  i_bigImage_path:string[];

constructor(private CartdataService: CartdataService, private router: Router, private http: HttpClient) {
    this.router.events.subscribe(
      () => window.scrollTo(0, 0)
    );
  }
 ngOnInit() {
    this.CartdataService.cast.subscribe(totalItems => this.nCount = totalItems);
    this.CartdataService.i_cast_Product_Path.subscribe(big_Image_Path => this.i_path[0] = big_Image_Path);
    this.CartdataService.j_cast_Product_Path.subscribe(small_Image_Path => this.j_path[1] = small_Image_Path);
    this.CartdataService.k_cast_Product_Path.subscribe(selected_Image_Path => this.k_path[2] = selected_Image_Path);

    this.i_path[0][0]['big_Images'] = this.i_bigImage_path;
  }

} 

这里我需要将每个路径分配给一个局部变量,以便将路径传递给 HTML 页面。

【问题讨论】:

  • 您正在使用 Angular 4.3 引入的 HttpClient 模块。并且您没有使用角度 4。编辑您的问题以避免进一步混淆
  • 通过this

标签: angular


【解决方案1】:
this.http.get(`http://localhost:abc/api/data/GetImage/?imageName=${this.current_product}`)
  .subscribe(data => {
  ......

这里的 data 不会是您期望的 json 有效负载。它是一个 http 响应,应该首先转换为 json 对象。试试这个:

this.http.get(`http://localhost:abc/api/data/GetImage/?imageName=${this.current_product}`)
  .map(r => r.json())
  .subscribe(data => {
  ......

【讨论】:

  • 显示错误:“对象”类型上不存在属性“json”
  • @Alexander Leonov in HttpClient 默认情况下需要 JSON 响应,因此不再需要显式解析 JSON 响应
  • @Nikson 如果您使用的是map 运算符,则需要导入它,语法从 RxJS v5.5.2 开始更改为 import {map} from 'rxjs/operators';
  • 我按照你说的做了一切,但没有任何改变
【解决方案2】:

首先在服务类的顶部导入'rxjs/Rx'。然后使用 map 运算符并从服务返回响应为 json 并在组件中处理 json。例如:

 getData(){
     return this.http.get('http://localhost:abc/api/data/GetImage/?imageName=${this.current_product}')
      .map((response: Response) =>{ return response.json()})
      .catch((error: Response) => { 
            return Observable.throw(error);
         });
  }

【讨论】:

  • 我如何才能看到我是否从 API 获得响应
  • @Vikas Garg in HttpClient 默认情况下需要 JSON 响应,因此无需再显式解析 JSON 响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2013-10-04
  • 1970-01-01
相关资源
最近更新 更多