简体   繁体   中英

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. 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

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.

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.

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

在此处输入图片说明

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

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

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.

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. It is an http response which should be converted to json object first. 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. And then use map operator and return response as json from service and handle json in component. 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);
         });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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