0

我目前正在尝试了解 NGXS 的工作原理,因此我能够设置状态和操作,但是当我调用我的服务并尝试将状态放入变量中时,我得到了一个 observable。

附件是代码和我从控制台得到的内容,我试图在我的应用程序启动时获取项目列表,所以基本上我有 2 个状态,客户端数组将存储来自服务的响应和加载状态,它将改变如果我得到回复,则为假,这是我第一次尝试处理这个概念,所以提前感谢您的帮助

  import { State, Action, StateContext, Selector } from "@ngxs/store";
  import { Client } from "../models/client-model";
  import { GetAllClients } from "../actions/client.actions";
  import { ClientService } from "../services/client.service";
  import { tap } from 'rxjs/operators';

  export class ClientStateModel {
    clients: Client[];
    loading: boolean;
  }

  @State<ClientStateModel>({
    name: "clients",
    defaults: {
      clients: [],
      loading: true
    }
  })
  export class ClientState {
    constructor(private _clientService: ClientService) {}

    @Action(GetAllClients)
    getClients(ctx: StateContext<ClientStateModel>, action: GetAllClients){
      return this._clientService.getClients().pipe(tap(clientsList => {
        const state = ctx.getState();
        ctx.setState({
          ...state,
          clients: clientsList,
          loading: false
        });
      }))
    }
  }

这是服务

  import { Injectable } from '@angular/core';
  import { HttpClient, HttpHeaders } from '@angular/common/http';
  import { Observable } from 'rxjs';
  import { environment } from '../../environments/environment';

  @Injectable()
  export class ClientService {
    public url: string;

    constructor(
      private _http: HttpClient
    ) {
      this.url = environment.apiURL;
    }

    getClients(): Observable<any> {
      const headers = new HttpHeaders({'Content-Type': 'application/json'});
      return this._http.get(`${this.url}get-clients`,{headers: headers});
    }
  }

这将是我消耗状态的尝试

  import { Component, OnInit } from "@angular/core";
  import { Client } from "./models/client-model";
  import { Router } from "@angular/router";
  import { Store } from "@ngxs/store";
  import { GetAllClients } from "./actions/client.actions";
  import { Observable } from "rxjs";

  @Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
  })
  export class AppComponent {
    title = "Managed Services Dashboard";
    Clients: Observable<Client>;
    isLoading;

    constructor(private store: Store, private _router: Router) {}

    ngOnInit(): void {
      this.getClients();
    }

    getClients() {
      this.store.dispatch(new GetAllClients()).subscribe(result => {
        this.Clients = this.store.select(state => state.clients.clients);
      })
    }

    goToSelectedClient(client) {
      console.log(client);
      this._router.navigate(["client-details"]);
    }
  }

这就是我在控制台中得到的。

安慰

4

1 回答 1

0

好的,首先在服务上,如果您要返回客户端列​​表,则可以使返回类型更具体:

getClients(): Observable<Client[]> {
  const headers = new HttpHeaders({'Content-Type': 'application/json'});
  return this._http.get(`${this.url}get-clients`,{headers: headers});
}

接下来,获取客户端的操作不需要操作参数,因为您没有在其中传递任何数据。它也可以像这样使用patchState:

@Action(GetAllClients)
getClients(ctx: StateContext<ClientStateModel>) {
    return _clientService.getClients().pipe(
        tap ( (clients: Client[]) => {
            ctx.patchState({ clients });
        }),
    );
}

在您的组件中,您可以使用 @Select 来获取有关客户端状态更改的 observable:

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent {
    @Select(ClientState) clientState$: Observable<ClientStateModel>;
    title = "Managed Services Dashboard";
    isLoading;
    .
    .
    .
    getClients() {
      this.store.dispatch(new GetAllClients());
    }

在组件的其他地方,或者在模板中,你可以使用 clientState$ observable:

    <div class="list-group">
      <a
        class="list-group-item"
        style="cursor: pointer"
        *ngFor="let client of (clientState$ | async).clients">
        {{ client.name }}
      </a>
    </div>

您还可以订阅 observable 以处理代码中的客户端列表更改。你会注意到我删除了对调度的订阅。指定返回 void,但可用于确定您的操作处理程序中是否发生错误(例如 HTTP 错误) - 您希望在组件中处理。

于 2018-08-15T13:52:46.807 回答