【问题标题】:How to share data between components that are not related? Angular 6 [duplicate]如何在不相关的组件之间共享数据? Angular 6 [重复]
【发布时间】:2019-09-05 19:00:45
【问题描述】:

我有两个组件,其中第二个根据第一个组件中选择的名称而变化。

如果我在第一个组件中选择“Bryan”,我的服务应该在数据库中获取有关 Bryan 的信息并移至我的第二个组件,因为它具有生成包含信息的表的功能。

我尝试使用 Subject 类,但无法将发射与可观察的 HTTP 请求的返回关联起来。

模板

<form class="mt-4" [formGroup]="managerForm">
  <ng-container *ngFor="let teamSale of teamSales">
    <label for="ManagerName" class="mt-2">{{ teamSale }}</label>
    <select id="ManagerName" class="form-control form-control-sm" formControlName="ManagerName" (change)="getAccountsByName()">
      <ng-container *ngFor="let manager of managers">
        <option *ngIf="manager.Team === teamSale" [value]="manager.Name">{{ manager.Name }}</option>
      </ng-container>
    </select>
    <hr>
  </ng-container>
</form>

服务

import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';

import { Account } from 'src/app/models/account-model';

@Injectable({ providedIn: 'root' })
export class QuotationService {

    private urlAPI: string = 'http://localhost:9095';

    private quotationByManegerSource = new Subject<Account[]>();
    public quotationByManeger$ = this.quotationByManegerSource.asObservable();

    constructor(private http: HttpClient) { }

    public getAccountsByName(managerName: string): Observable<Account[]> {
        const url: string = `${this.urlAPI}/get-accounts-by-name/${managerName}`
        return this.http.get<Account[]>(url)
    }
}

我希望在选择名称时,将数据库中引用该名称的信息传递给另一个组件。

并让第二个组件监听第一个组件中所做的更改。

【问题讨论】:

标签: javascript mysql node.js angular typescript


【解决方案1】:

您可以在服务中创建主题

messageSource: Subject&lt;string&gt;; 并在你的构造函数中实例化

this.messageSource = new Subject<string>();

在您的组件中,您可以这样做,

this.yourService.messageSource.next('whatvermessage');

如果你想订阅它,你可以这样做

this.yourService.messageSource.asObservable().subscribe((value: string) => {

});

【讨论】:

  • 我在服务中创建了主题,但是如何将数据库返回的值与此主题相关联?我需要发出从数据库返回的值,然后在另一个组件中检索它。
  • 只需将值设置为主题
  • 它给出了类型冲突。我该怎么做?
  • 冲突是什么
猜你喜欢
  • 2019-02-03
  • 2019-04-28
  • 2019-08-07
  • 1970-01-01
  • 2020-10-21
  • 2021-05-03
  • 2021-06-24
  • 2019-08-04
  • 2018-02-17
相关资源
最近更新 更多