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

时间:2018-08-14 21:30:11

标签: javascript angular6 ngxs

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

附带的是代码和我从控制台获得的内容,我试图在我的应用程序启动时获取项目列表,所以基本上我有2个状态的clients数组,用于存储来自服务的响应和加载状态如果我得到答复,它将变为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"]);
    }
  }

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

console

1 个答案:

答案 0 :(得分: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来观察客户端状态的变化:

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

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

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

相关问题