Angular 2:从http设置值进入Service

时间:2017-07-31 04:08:09

标签: angular typescript angular2-services

我正在尝试在Angular服务中设置一个变量,使其可用于我的组件。

  

quotation.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { SupplyersList } from '../pages/comparative-map/interfaces/comparative-map.interfaces';

@Injectable()
export class QuotationService {
    baseUrl: string;
    supplyers_list: SupplyersList[];

    constructor(private http: Http) {
        console.log('%c ▸QuotationService Initialized...', 'color:#0098f1');
        this.baseUrl = 'http://104.197.212.14:3000';
        this.quotationId = 10;

        this.getQuotationSupplyers().subscribe(supplyers => {
            this.supplyers_list = supplyers;
        });

    }
    getQuotationSupplyers() {
        // return this.http.get('/app/data/quotation_supliers.data.json').map(res => res.json());
        return this.http.get(this.baseUrl  + '/providers?id=' + this.quotationId, this.jwt()).map((response: Response) => response.json());
    }

    // private helper methods
    private jwt() {
        // create authorization header with jwt token
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            let headers = new Headers({ 'x-access-token': currentUser.token });
            return new RequestOptions({ headers: headers });
        }
    }
}
  

比较-map.interfaces

export interface SupplyersList {
  name: string;
  logo: string;
  id: number;
  position: number;
  destination_distance: number;
  itens: SupplyersItens[];
  checked: boolean;
}
  

比较-details.component.ts

import { Component, Input } from '@angular/core';
import { QuotationService } from '../../../../services/quotation.service';
import { QuotationItens } from '../../interfaces/comparative-map.interfaces';
import { BestPrice } from '../../interfaces/comparative-map.interfaces';
import { SupplyersList } from '../../interfaces/comparative-map.interfaces';
import { SupplyersItens } from '../../interfaces/comparative-map.interfaces';

@Component({
  selector: 'comparative-details',
  templateUrl: './comparative-details.component.html',
  styleUrls: ['./comparative-details.component.css']
})
export class ComparativeMapDetailsComponent {

  /** quotation data */
  @Input('quotationItens')
  quotation_itens: QuotationItens[];
  @Input('destinationName')
  destination_name: string;
  supplyers_list: SupplyersList[];

  constructor(private QuotationService: QuotationService) {

    this.supplyers_list = this.QuotationService.supplyers_list;

  }

  setSelectedSupplyer(event: any) {
    const supplyer_id = Number(event.target.value);

    this.supplyers_list.forEach(function(supplyer){
      if (supplyer.id !== supplyer_id) {
        supplyer.checked = false;
      }
    });
    this.QuotationService.setSelectedSupplyer(event);
  }
}

enter image description here

当我尝试从QuotationService访问suppliers_list时,我得到了这个:

enter image description here

我正在尝试将其用于所有应用程序

2 个答案:

答案 0 :(得分:0)

感谢@Ankit Rana@Rahul Naik我发现我需要将supplyers_list设置为Subject

以上更新:

  

quotation.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { SupplyersList } from '../pages/comparative-map/interfaces/comparative-map.interfaces';

import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';

@Injectable()
export class QuotationService {
    baseUrl: string;
    private supplyers_list = new Subject<any>();

    constructor(private http: Http) {
        console.log('%c ▸QuotationService Initialized...', 'color:#0098f1');
        this.baseUrl = 'http://104.197.212.14:3000';
        this.quotationId = 10;

        this.getQuotationSupplyers().subscribe(supplyers => {
            this.supplyers_list = supplyers;
        });

    }

    returnAvailableSupplyersList(): Observable<any> {
        return this.available_supplyers.asObservable();
    }

    getQuotationSupplyers() {
        // return this.http.get('/app/data/quotation_supliers.data.json').map(res => res.json());
        return this.http.get(this.baseUrl  + '/providers?id=' + this.quotationId, this.jwt()).map((response: Response) => response.json());
    }

    // private helper methods
    private jwt() {
        // create authorization header with jwt token
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            let headers = new Headers({ 'x-access-token': currentUser.token });
            return new RequestOptions({ headers: headers });
        }
    }
}
  

比较-details.component.ts

import { Component, Input } from '@angular/core';
import { QuotationService } from '../../../../services/quotation.service';
import { QuotationItens, BestPrice , SupplyersList, SupplyersItens  } from '../../interfaces/comparative-map.interfaces';

import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'comparative-details',
  templateUrl: './comparative-details.component.html',
  styleUrls: ['./comparative-details.component.css']
})
export class ComparativeMapDetailsComponent {

  /** quotation data */
  @Input('quotationItens')
  quotation_itens: QuotationItens[];
  @Input('destinationName')
  destination_name: string;
  supplyers_list: SupplyersList[];

  subscription: Subscription;

  constructor(private QuotationService: QuotationService) {

      this.subscription =  this.QuotationService.returnQuotationSupplyers().subscribe(supplyers => {
          this.supplyers_list = supplyers;
      });

  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }

  setSelectedSupplyer(event: any) {
    const supplyer_id = Number(event.target.value);

    this.supplyers_list.forEach(function(supplyer){
      if (supplyer.id !== supplyer_id) {
        supplyer.checked = false;
      }
    });
    this.QuotationService.setSelectedSupplyer(event);
  }
}

非常感谢,伙计们。它救我了

答案 1 :(得分:-2)

Angular 2是类型脚本,类似于面向对象的语言。

在组件中,您可以按以下方式调用此方法。

this.QuotationService.getQuotationSupplyers(quotationId);