【发布时间】:2019-06-24 20:00:09
【问题描述】:
场景:
我有一个 api:
https://................../api/branches
在 api 中 /branches 表示 api 为多个 branches 和唯一的 ID 。每个 branch 将有自己的 contacts。
假设我想在 POSTMAN 中看到一个特定的 branch 联系人:
https://................../api/branches/88fe-cc12-we33/contacts88fe-cc12-we33 是一个分支 ID。
现在在我的应用程序中。我在一个名为 contacts 的组件中调用这个特定的 branch ID's contacts,方法是硬编码像 branch ID这个:
import { Component, Input, OnInit } from '@angular/core';
import { IContact } from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';
@Component({
selector: 'asw-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.css'],
})
export class ContactsComponent {
public contacts: IContact[];
constructor(public customersService: CustomersService) {}
public async ngOnInit(): Promise<void> {
this.contacts = await this.customersService.getContactList('88fe-cc12-we33');<==========
console.log(this.contacts);
}
}
customers.services.ts 文件
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { IBranch, IContact } from 'src/app/models/app.models';
@Injectable({
providedIn: 'root',
})
export class CustomersService {
private baseUrl : string = 'https://................../api/';
constructor(private http: HttpClient) {
}
public getBranchesInfo(branchId : string): Promise<IBranch> {
const apiUrl: string = 'https://................../api/branches/';
return this.http.get<IBranch>(apiUrl + branchId).toPromise();
}
public async getContactList(branchId: string): Promise<IContact[]> <=======
{
const apiUrl: string = `${this.baseUrl}branches/${'branchId'}/contacts`;
return this.http.get<IContact[]>(apiUrl).toPromise();
}
}
我想根据我选择的 branch 来调用 contacts,而不是硬编码和调用一个 branch 联系人,所以我创建了一个组件称为 branches 并且我在下拉列表中显示所有 branches,如下图所示:
分支组件代码:
HTML
<mat-form-field>
<mat-select placeholder="Select Branch">
<mat-option *ngFor="let branch of branches" [value]="branch.id">
{{branch.name}}
</mat-option>
</mat-select>
</mat-form-field>
TS
import { Component, OnInit } from '@angular/core';
import { CustomersService } from 'src/app/services/customers.service';
import { IBranch } from 'src/app/models/app.models';
@Component({
selector: 'asw-branch',
templateUrl: './branch.component.html',
styleUrls: ['./branch.component.css']
})
export class BranchComponent implements OnInit {
public branches: IBranch[];
constructor(public customersService: CustomersService) {}
public async ngOnInit(): Promise<void> {
this.branches = await this.customersService.getBranchesInfo('');
}
}
在上面的代码中,我在dropdown 中显示所有branches,现在我想将选择的branch id 发送到联系人 组件意味着到这里:
public async ngOnInit(): Promise<void> {
this.contacts = await this.customersService.getContactList('');<==========
}
因此它将根据发出的branch id 获取contacts。我知道我可以在parent 到child 组件通信中使用@Input 方法,但是这里两个(分支和联系人) 组件都是独立的组件。没有 父子关系。如何将id 从branches 组件传递给contacts 组件?
【问题讨论】:
标签: angular angular6 angular-services