简体   繁体   English

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

[英]Passing data between components using a service Angular

There are many examples around the web on this subject but none of them helped me.网上有很多关于这个主题的例子,但没有一个对我有帮助。 This is the scenario: I've got 2 components and a service.这是场景:我有 2 个组件和一个服务。 The two components aren't parent/children but are 2 independent components.这两个组件不是父/子组件,而是 2 个独立的组件。 One of them has a list of names, the other should load a table when one of the names is clicked.其中一个有一个名称列表,另一个应该在单击其中一个名称时加载一个表格。 This is my home.html with both components这是我的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>

Heroes sidenav component:英雄 sidenav 组件:

<div *ngIf="loadingData == true">
  <mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>
<nav *ngIf="loadingData == false">
  <p *ngFor="let item of heroesNames.results let i = index" [attr.data-index]="i">
    <button mat-button (click)="getHero(i)">
        {{item.name}} 
    </button>
  </p>
</nav>

On click getHero() is called correctly.单击时getHero()被正确调用。 This is the sidenav component ts:这是 sidenav 组件 ts:

import { Component, OnInit, Input } from '@angular/core';
import {SwCharactersServiceService} from '../sw-characters-service.service';
import {HeroesTableComponent} from '../heroes-table/heroes-table.component';

@Component({
  selector: 'app-heroes-sidenav',
  templateUrl: './heroes-sidenav.component.html',
  styleUrls: ['./heroes-sidenav.component.css']
})
export class HeroesSidenavComponent implements OnInit {
  heroesNames: any;
  heroData:any;
  loadingData = true;
  @Input() heroesTable: HeroesTableComponent;
  constructor(private _swService: SwCharactersServiceService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes() {
    this._swService.getCharacters().then(result => {
      this.loadingData = false;
      this.heroesNames = result;
    });
  }

  getHero(index) {
    this._swService.getHero(index);
  }
}

and this is the service:这是服务:

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

I can correctly see the console.log(index) but the request doesn't work.我可以正确地看到console.log(index)但请求不起作用。 There is no request initiated in chrome console network tab.在 chrome 控制台网络选项卡中没有发起请求。 This is the component with the table:这是带有表格的组件:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import {SwCharactersServiceService} from '../sw-characters-service.service';

@Component({
  selector: 'app-heroes-table',
  templateUrl: './heroes-table.component.html',
  styleUrls: ['./heroes-table.component.css']
})
export class HeroesTableComponent implements OnInit {
  loadingData = true;
  heroData :any;
  subscription: Subscription;

  constructor(private _swService: SwCharactersServiceService) {
    this.subscription = this._swService.getHero(1).subscribe(result => { this.heroData = result; });
    console.log(this.heroData);
  }

  ngOnInit() {

  }

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

There are 2 problems now:现在有2个问题:

1) As you can see I wrote this._swService.getHero(1) without passing a dynamic param. 1) 如您所见,我在没有传递动态参数的情况下编写了this._swService.getHero(1) How does it work?它是如何工作的? How can I pass the correct index?如何传递正确的索引?

2) The service doesn't fire and I haven't got any result. 2)服务没有启动,我没有得到任何结果。

Is there any other way to do that?有没有其他方法可以做到这一点?

Thanks.谢谢。

you can use BehaviourSubject to pass the index value and send the query request as the list is cliked in the service您可以使用 BehaviourSubject 传递索引值并在服务中单击列表时发送查询请求

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
 public index: BehaviorSubject<number> = new BehaviorSubject<number>(null);

in the sidenav component在 sidenav 组件中

getHero(index) {
    this._swService.index.next(index);
  }

in the hero table component在英雄表组件中

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

You missed to subscribe to _swService.getHero() .您错过了订阅_swService.getHero() If not subscribed to a method which returns an Observable , then it wont be invoked.如果未订阅返回Observable的方法,则不会调用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM