加载我的组件后我无法读取我的状态,状态正在正确改变

i can't read my state once i load my component, state is properly changing

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

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

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

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

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

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 来获取有关客户端状态更改的可观察对象:

@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>

您还可以在代码中订阅可观察对象来处理客户端列表更改。您会注意到我删除了对调度的订阅。这被指定为 return 空值,但可用于确定您的操作处理程序中是否发生了错误(比如 HTTP 错误)- 您希望在组件中处理。