【问题标题】:Angular 2 pass value to serviceAngular 2将价值传递给服务
【发布时间】:2017-05-25 01:07:22
【问题描述】:

我知道如何在嵌套组件之间传递数据。但是我有一个从 REST API 获取一些数据的服务。当我单击并运行函数时,我需要更改服务中的 URL。我需要将 ID 传递给我的服务并更改我的 URL。

我是我的组件:

showUnitDetails(selectedUnit) {
    this.unitId = selectedUnit;
    this.unitDetails = true;
    this._unitService.getUnit(this.unitId).subscribe(resUnitData => this.unit = resUnitData, err => alert('Error'));
}

在我的服务中:

getUnit(id: unitId){
    return this._http.get(this._url).map((response: Response) => response.json());
}

但是当我保存我的服务时,我收到了错误"Cannot find name unitId"

【问题讨论】:

  • 您应该将您的代码展示给您迄今为止尝试过的内容,否则唯一可以给出的建议是:使用参数。
  • 自行删除帖子。

标签: angular rest angular-services


【解决方案1】:

我给你做了一个简单的例子,展示了如何连接组件和 http 服务以及你可以传入 id 和 url 的参数。

模块:

import { NgModule } from "@angular/core"

//A Module
@NgModule({
  declarations: [MyComponent],
  providers: [MyService],
})
export class MyModule {}

组件:

import { Component } from "@angular/core"
import { MyService } from 'path-to-service';

//The Component
@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
})

export class MyComponent {
  private id: number;
  private url: string;

  constructor(public myService: MyService) {}

  ngOnInit() {
    this.id = 123;
    this.url = '/api/stuff';

    this.myService
      .getStuff(this.id, this.url)
      .subscribe(response => {
          console.log(response);
        },
        error => {
          console.log(error);
        })
  }
}

服务:

import { Injectable } from '@angular/core';
import { Http } from "@angular/http"

//The Service
@Injectable()
export class MyService {
  constructor(private http: Http) {}

  getStuff(id: number, url: string) {
    const urlWithId = url + id;

    return this.http
      .get(urlWithId)
      .map(res => res.json())
  }
}

【讨论】:

  • 我的组件函数如下所示:showUnitDetails(selectedUnit) { this.unitId = selectedUnit; this.unitDetails = true; this._unitService .getUnit(this.unitId) .subscribe( resUnitData => this.unit = resUnitData, err => alert('Error') ); } 在我的服务中:constructor(private _http: Http){} getUnit(id: unitId){ return this._http .get(this._url) .map((response:Response) => response.json()); } 但是当我保存我的服务时,我收到错误“找不到名称 unitId”。
  • 试试getUnit(id:number)。它会引发错误,因为您可能尚未创建模型 unitId 您不需要用于描述单个属性的模型。模型用于描述具有多种类型的属性集合。
  • 另外你没有使用你传入服务的id,我想你需要将它添加到你的url。
  • 你能帮我解决另一个问题码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 2016-09-17
  • 1970-01-01
相关资源
最近更新 更多