Angular将变量从组件传递到服务

时间:2017-05-26 16:10:53

标签: angular typescript

我正在尝试获取变量并将其从方法传递到服务中。

来自calibration-detail.component.ts

private heroID: number;
getTheHeroID() {
    this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id));
}

到step.service.ts

我不确定如何调用变量并将其存储到另一个变量中。 我想做的是:

private test:number = CalibrationDetailComponent.heroID //传入step.service.ts

private test:number = CalibrationDetailComponent.getTheHeroID(); //进入step.service.ts

这样做最好的方法是什么?

step.service.ts

import { CalibrationDetailComponent } from './calibration-detail/calibration-detail.component';
import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Step } from './step.class';
import { Hero } from './hero.class';
import { Observable } from "rxjs/Rx";
import { ActivatedRoute, Params } from '@angular/router';
import { HeroService } from './hero.service';

@Injectable()
export class StepService {

  hero: Hero;
  private headers = new Headers({'Content-Type': 'application/json'});
  private stepsUrl;  // URL to web api
  private heroID: number;

  constructor (private http: Http, private route: ActivatedRoute, public heroService: HeroService) { 
    //this.heroService.getHero(+['id']).map(data =>(this.heroID = data.id)); //Get the hero id to know which steps to use

  //defaulting to first one
  if (this.heroID = 1){
   this.stepsUrl = 'api/stepsLiftSensor';
 } else if(this.heroID = 2){
   this.stepsUrl = 'api/BucketSensor';
 } else if(this.heroID = 3){
   this.stepsUrl = 'api/EmptyBucketSensor';
 } else if(this.heroID = 4) {
   this.stepsUrl = 'api/FullBucketSensor';
 }
}

  getSteps(): Observable<Step[]> {
    return this.http.get(this.stepsUrl)
               .map(response => response.json().data as Step[]);
  }

  getStep(id: number): Observable<Step> {
    const url = `${this.stepsUrl}/${id}`;
    return this.http.get(url)
      .map(response => response.json().data as Step);
  }

} 

校准detail.component.ts

import { Component, OnInit, Input, Output } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Hero } from '../hero.class';
import { Step } from '../step.class';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { InMemoryDataService } from '../in-memory-data.service';
import { HeroService } from '../hero.service';
import { StepService } from '../step.service';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

@Component({
  moduleId: module.id,
  selector: 'app-calibration-detail',
  templateUrl: './calibration-detail.component.html',
  styleUrls: ['./calibration-detail.component.css']
})

export class CalibrationDetailComponent implements OnInit {
  @Input()
  hero: Hero;
  step: Step;

  private mainStepText: String = "Test" //Main window
  private statusStepText: String = "Calibration Successfull"; //Status window placeholder
  private labelText: String = "Parking Brake Status \nImpl Lockout Switch \nLift Linkage DC";
  private outputText: String = "Disengaged \nLocked Out \n0%";
  private currentStep: number = 0 //Variable for the current step
  private hideThis: boolean = true;
  private heroID: number;

  constructor(
     private heroService: HeroService,
     private stepService: StepService,
     private route: ActivatedRoute,
     private location: Location,
     private http: Http,
  ) { }


  ngOnInit(): void { 
     this.route.params
       .switchMap((params: Params) => this.heroService.getHero(+params['id']))
       .subscribe(hero => this.hero = hero);

     this.route.params
       .switchMap((params: Params) => this.stepService.getStep(+params['id']))
       .subscribe(step => this.step = step);
  }

  goBack() {
    //Goes back to previous step, if there is no previous step it takes you back to location you were at
    if(this.currentStep > 1){
      this.currentStep --;
      this.stepService.getStep(this.currentStep).subscribe(data => (this.mainStepText = data.name));
    } else {
      this.location.back();
    }
  }

  ok() {
    //Placeholder code for now
    this.location.back();
  }

  next() {
    //Assuming there is another step it pulls the next step up, else it says "End of steps"
    if (this.currentStep < 10) { //make sure dont go past number of steps
       this.currentStep ++;
       this.hideThis = false;
       this.stepService.getStep(this.currentStep).subscribe(data => (this.mainStepText = data.name)); //Handles returned observable and sets the data it contains to local variable
  } else {
      this.mainStepText = "End of steps.";
      this.hideThis = true;
    }
  }

  isValid() {
    if (this.currentStep < 1){
      return this.isValid;
    } 
  }

  getTheHeroID() {
    this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id));
  }
}

hero.service.ts

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import 'rxjs/Rx';
import { Hero } from './hero.class';
import { Observable } from "rxjs/Rx";

@Injectable()
export class HeroService {

  private headers = new Headers({'Content-Type': 'application/json'});
  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(private http: Http){ }

  getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
               .map(response => response.json().data as Hero[]);
  }

  getHero(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get(url)
      .map(response => response.json().data as Hero);
  }
}

2 个答案:

答案 0 :(得分:1)

要将值传递给组件中的服务,您可以执行以下操作:

export class SomeService {
    private test: number;

    public setTest(value: number) {
        this.test = value;
    }
}

@Component({
    selector: 'prefix-some',
    template: `
        <button (click)="sendValueIntoService(1)"></button>
    `
})
export class SomeComponent {

    private test: number;

    constructor(private _someService: SomeService) {}

    sendValueIntoService(value: number) {
        this._someService.setTest(value);
    }
}

答案 1 :(得分:0)

如果我们想将“帐户”(具有来自component.ts的某些数据的变量)传递给服务 我们可以像下面这样通过:

首先在service.ts中创建一个新变量 service.ts:

test : any;

component.ts:

accounts = [];

constructor(){
    this.service.test = this.accounts
}

最后,将从服务中创建的新变量分配给帐户中的数据