简体   繁体   English

Angular4:如何从模型类检索数据

[英]Angular4 : How to retrieve data from model class

I am working in an Angular4 application ,In this I am storing API response to model class ,Now I want to retrieve data from model class in specific component,I have tried something but I can't get the values. 我正在Angular4应用程序中工作,在此我存储了对模型类的API响应,现在我想从特定组件中的模型类中检索数据,我尝试了一些操作但无法获取值。

Model class 模型类

export interface Images {
  big_Images: BImage[];
  small_Images: Simage[];
  selected_Product_Images: SelectedImage[]
}

export interface BImage {
  big_Images: string;
}

export interface Simage {
  small_Images: string;
}

export interface SelectedImage {
  selected_Product_Image: string;
}

component 零件

import { Component } from '@angular/core';
import { CartdataService } from './cartdata.service';
import { Images } from './model';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor(private CartdataService: CartdataService) {}

   images : Images;

   ngOnInit() {
    this.CartdataService.i_cast_Product_Path.subscribe( (response : Images ) =>
    { this.images = response; });
  }
}

API res API资源

在此处输入图片说明

I want to print each data in a span tag 我想在span标签中打印每个数据

在此处输入图片说明

Try this, I assumed your response JSON matches the interface. 尝试此操作,假设您的响应JSON与接口匹配。

Option 01 选项01

cartdata.service.ts cartdata.service.ts

Import below modules 导入以下模块

import { Observable } from 'rxjs';
import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";

get_Product_Path(pName: string) : Observable<any> {
     let headers = new Headers({ 'Content-Type': 'application/json' });
     let options = new RequestOptions({ headers: headers });
    this.current_product = pName.trim();
    return this.http.get(`http://localhost:abc/api/data/GetImage/?imageName=${this.current_product}`,options);

  }

app.component.ts app.component.ts

ngOnInit() {
    this.CartdataService.get_Product_Path('').subscribe(response =>
    { 
        console.log(response);
        this.images = response.json(); 
    });
  }

I hope this will help you. 我希望这能帮到您。 If you have any problem or doubt let me know. 如果您有任何问题或疑问,请告诉我。

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

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