我正在做一个项目,要求加载和选择客户端(不是用户,而是更像客户)。
不幸的是,我似乎无法订阅我在组件中加载的可观测数据。我已经尝试了所有可能的解决方案,我可以找到网上,但也许我的经验不足的角度是阻止我找到正确的一个。
现在的工作是:
-在选择框中加载客户端
-为选择框中的选项提供客户端ID值
-将客户端的ID发送到client.service并将选定的客户端保存为可观察的
所以我唯一的问题是组件没有注意到client.service中的可观察到的变化。
这是我的client.service.ts:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ApiService } from '../api.service';
import { Client } from './client';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';

@Injectable()
export class ClientService {

    clients$: Observable<Client[]>;
    client: Client;
    selectedClient$: Observable<Client[]>;

    constructor(private api: ApiService) {
        this.clients$ = this.getAll();
    }

    public getAll(): Observable<Client[]> {
        return this.api.get<Client[]>('clients');
    }

    public setSelectedClient(clientId: number) {
        this.clients$ = this.getAll();
        if (clientId == null) {
            // Do nothing
        } else {
            this.selectedClient$ = this.clients$.map(arr =>
            { return arr.find(client => client.id === clientId) });
        }
    }

    public getSelectedClient() : Observable<Client> {
        return this.selectedClient$;
    }

}

我的组件,带注释的部分显示了修复我的问题的一些尝试:
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { ClientService } from "../client/client.service";
import { Client } from "../client/client";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';

@Component({
    selector: 'app-left-menu',
    templateUrl: './left-menu.component.html',
    styleUrls: ['./left-menu.component.css']
})

export class LeftMenuComponent implements OnInit {

    selectedClient$ : Observable<Client>;
    client: Client = new Client();
    clients$ : Observable<Client[]>;

    constructor(private clientService: ClientService) {

    }

    ngOnInit() {
        // this.clientService.getSelectedClient().subscribe(selectedClient$ => {
        //     this.selectedClient$ = Observable.of(selectedClient$);
        // });
        // //
        // this.clientService.getAll().subscribe(clients$ => {
        //     this.clients$ = Observable.of(clients$);
        // });

        this.selectedClient$ = this.clientService.getSelectedClient();
        this.clients$ = this.clientService.getAll();
    }

    public setSelectedClient(clientId: number) {
        this.clientService.setSelectedClient(clientId);
    }

}

以及我用来显示和选择客户机的HTML部分:
 <select #selectClient [ngModel]="selectedClient$ | async"
   (ngModelChange)="setSelectedClient(selectClient.value)">
        <option *ngFor="let client of clients$ | async" [value]="client.id">
            {{ client.firstName }}
            {{ client.preposition }}
            {{ client.lastName }}
        </option>
 </select>

 <!-- Displaying selected client -->
 <h2 *ngIf="selectedClient$">{{(selectedClient$ | async)?.firstName}}
 </h2>

如果有人能帮我解决这个问题,我将不胜感激,谢谢!

最佳答案

Demo
使用[ngValue]而不是[value]将客户机对象本身绑定到[ngModel]指令,我还使用Subject轻松通知新选定客户机的其他订户:
客户服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import { Client } from './client';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
@Injectable()
export class ClientService {

    clients$: Observable<Client[]>;
    client: Client;
    selectedClient$: Subject<Client> = new Subject<Client>();

    //...
    public setSelectedClient(client: Client) {
        if (client)
            this.selectedClient$.next(client);
    }
    //...
}

组件.ts:
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { ClientService } from './client.service';
import { Client } from './client'


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

    selectedClient : Client;
    client: Client = new Client();
    clients$ : Observable<Client[]>;

    constructor(private clientService: ClientService) {

    }

    ngOnInit() {
        //...
        this.clients$ = this.clientService.getAll();
        this.clientService.selectedClient$.subscribe(console.log)
    }

    setSelectedClient(client : Client){
      this.selectedClient = client;
      this.clientService.setSelectedClient(client)
    }
}

模板:
<select #selectClient [ngModel]="selectedClient"
(ngModelChange)="setSelectedClient($event)">
     <option *ngFor="let client of clients$ | async" [ngValue]="client">
         {{ client.firstName }}
         {{ client.preposition }}
         {{ client.lastName }}
     </option>
</select>

关于javascript - Angular 4:订阅可观察,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47740365/

10-09 20:52