Javascript 使用服务在组件之间传递数据

Javascript 使用服务在组件之间传递数据,javascript,angular,typescript,service,components,Javascript,Angular,Typescript,Service,Components,网上有很多关于这个问题的例子,但没有一个对我有帮助。这是一个场景:我有两个组件和一个服务。这两个组件不是父/子组件,而是两个独立的组件。其中一个具有名称列表,另一个应在单击其中一个名称时加载一个表。这是我的home.html,包含两个组件 <div class="material-docs-app"> <div class="docs-primary-header"> <h1>Yep!</h1> </div>

网上有很多关于这个问题的例子,但没有一个对我有帮助。这是一个场景:我有两个组件和一个服务。这两个组件不是父/子组件,而是两个独立的组件。其中一个具有名称列表,另一个应在单击其中一个名称时加载一个表。这是我的
home.html
,包含两个组件

<div class="material-docs-app">
  <div class="docs-primary-header">
      <h1>Yep!</h1>
  </div>
    <div fxLayout="row" fxLayout.xs="column" class="component-layout-body">
        <app-heroes-sidenav></app-heroes-sidenav>
        <app-heroes-table #heroesTable fxFlex="1 2 calc(15em + 20px)" style="width: 100%"></app-heroes-table>
    </div>
</div>
这就是服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import 'rxjs/add/operator/map'

import {Observable} from 'rxjs/Observable';

@Injectable({
  providedIn: 'root'
})
export class SwCharactersServiceService {
  param:any;
  constructor(private http: HttpClient) { }

  getCharacters(): Promise<any[]> {
    return this.http.get<any[]>("https://swapi.co/api/people/")
    .toPromise()
    .then(result => result) 
    .catch(this.handleError);
  }

  getHero(index): Observable<any>{
    console.log(index);
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    return this.http.get("https://swapi.co/api/people/" + index, {
        headers: headers
    }).map(res => res );
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}
现在有两个问题:

1) 如您所见,我编写了
这个。_swService.getHero(1)
而没有传递动态参数。它是如何工作的?如何通过正确的索引

2) 服务没有启动,我也没有得到任何结果

还有别的办法吗


谢谢。

您错过了订阅
\u swService.getHero()
。如果未订阅返回可观察的
方法,则不会调用该方法

getHero(index) {
    this._swService.getHero(index).subscribe(
                  (resp) => {
                     // manipulate your response here
                     console.log(resp);  
                  },
                  (err) => {}
          );
}

您可以使用Behavior Subject传递索引值,并在剪切列表时发送查询请求 在职

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
 public index: BehaviorSubject<number> = new BehaviorSubject<number>(null);
在英雄表组件中

getHero(index) {
    this._swService.index.next(index);
  }
ngAfterViewInit(){
   this._swService.index.subscribe(index=>{
      if(index){
        this._swService.getHero(index).subscribe(result => { this.heroData = result; });
      }
   })
}

好的,它现在可以工作了,但是接收结果的组件呢?您的方式已经部分纠正了。因为我必须将结果传递到另一个组件中才能使用该数据创建表,请检查更新的代码以处理响应。BehaviorSubject的导入在服务中?是的,索引的声明也是公共索引:BehaviorSubject=new BehaviorSubject(null);我很高兴我能帮上忙,我不知道为什么,但每次点击都会有12个请求。这正常吗?getHero()函数是否仅在sidenav组件中调用?
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
 public index: BehaviorSubject<number> = new BehaviorSubject<number>(null);
getHero(index) {
    this._swService.index.next(index);
  }
ngAfterViewInit(){
   this._swService.index.subscribe(index=>{
      if(index){
        this._swService.getHero(index).subscribe(result => { this.heroData = result; });
      }
   })
}