简体   繁体   English

Angular:如何在服务文件中接收API响应

[英]Angular : How to receive API response in service file

I am working on an Angular application, In this, I am using HttpClient module to consume an API response. 我正在开发一个Angular应用程序,在这里,我正在使用HttpClient模块来使用API​​响应。 I have developed something but I always got "undefined" as a response. 我已经开发出一些东西,但是我总是得到“未定义”作为响应。

Here I have two components and one service file, From the Landingpage.component.ts I have onclick event that will pass the "product name" to service file , From the service file (cartdata.service.ts) I pass the product name to API 在这里,我有两个组件和一个服务文件,从Landingpage.component.ts,我有onclick事件,它将“产品名称”传递给服务文件,从服务文件(cartdata.service.ts),我将产品名称传递给API

API will return the image path of the particular product.I receive the API response inside the service and process it then passes the data to the mycart.component.ts component of that component I am assigning the path to the respected HTML pages. API将返回特定产品的图像路径。我在服务内部收到API响应,然后对其进行处理,然后将数据传递到该组件的mycart.component.ts组件,我将路径分配给受关注的HTML页面。

What I want to do is, get all image path of the specific product From the API response and assign it to the respected HTML pages. 我要做的是,从API响应中获取特定产品的所有图像路径,并将其分配给受尊重的HTML页面。

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

在此处输入图片说明

This is the response Which I have received from the 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);
  }
}

This is my cartdata.service.ts 这是我的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);
      });
  }
}

This is my my-cart.component.ts 这是我的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;
  }

} 

Here I need to assign each path to a local variable for passing path to HTML pages. 在这里,我需要将每个路径分配给本地变量,以将路径传递给HTML页面。

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

Here data won't be the json payload that you'd expect. 这里的data将不是您期望的json负载。 It is an http response which should be converted to json object first. 这是一个http响应,应首先将其转换为json对象。 Try this: 尝试这个:

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

Firstly import 'rxjs/Rx' at top in service class. 首先在服务类的顶部导入“ rxjs / Rx”。 And then use map operator and return response as json from service and handle json in component. 然后使用地图运算符并从服务返回响应作为json并处理组件中的json。 eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM