簡體   English   中英

Angular:如何在服務文件中接收API響應

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

我正在開發一個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頁面。

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

首先在服務類的頂部導入“ rxjs / Rx”。 然后使用地圖運算符並從服務返回響應作為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);
         });
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM