将变量从组件传递到服务的角度 [英] Angular passing a variable from a component to a service

查看:62
本文介绍了将变量从组件传递到服务的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to take a variable and pass it from a method into a service.

来自Calibration-detail.component.ts

from calibration-detail.component.ts

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

到step.service.ts

to step.service.ts

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

I'm not sure how to call the variable and store it into another variable. What I want to do is:

私人测试:数字= CalibrationDetailComponent.heroID//传递到step.service.ts

private test: number = CalibrationDetailComponent.heroID //pass into step.service.ts

私人测试:数字= CalibrationDetailComponent.getTheHeroID();//传递到step.service.ts

private test: number = CalibrationDetailComponent.getTheHeroID(); //pass into step.service.ts

执行此操作的最佳方法是什么?

What's the best way to go about doing this?

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);
  }

} 

calibration-detail.component.ts

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

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);
  }
}

推荐答案

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

To pass a value into a service from a component you would do something like:

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);
    }
}

这篇关于将变量从组件传递到服务的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆