路由时堆栈订阅 angular

Stack subscription when routing angular

我有一个调用 Observable 服务的方法。我订阅它并在导航时销毁它,但是当我导航回来时我的方法堆栈结果

Note: Angular CLI: Version 13.0.2 | npm 8.1.0

  //home component
  
  public workList:workModel[] = [];
  serviceSubscription:Subscription;

  constructor(
    public workService: WorkServices
  ) {

    this.serviceSubscription = this.getWorkList();

   }
  
  ngOnInit(): void {
    //this.serviceSubscription = this.getWorkList();
  }

  ngOnDestroy(): void {
    this.serviceSubscription.unsubscribe();
  }

  getWorkList(){

    this.workList = [];

    return this.workService.getWorks().subscribe((resp:Array<workModel>) => {
      this.workList = resp.reverse();
      console.log("work list ->", this.workList);
    })
  }
  
  //**************************************************************
  //service
  @Injectable({
    providedIn: 'root'
})
export class WorkServices {

    private URL = "http://localhost:3000/work";
    private works:workModel[];

    constructor(
        public http:HttpClient
        ){
            this.works = new Array<workModel>();
    }

    getWorks(){

        return this.http.get(this.URL).pipe(map((resp:any) => {
            resp.forEach((w:workModel) => {
                this.works.push(new workModel(
                    w.description,
                    w.client,
                    w.employees,
                    w.materials,
                    w.isFinished,
                    w.cost,
                    w.id
                )) 
            })
            return this.works;
        }));
    }

/*
Console

work list -> Array [ {…}, {…} ] // load page
work list -> Array(4) [ {…}, {…}, {…}, {…} ] // Navigate and back first time
work list -> Array(6) [ {…}, {…}, {…}, {…}, {…}, {…} ] // Navigate and back second time
*/

我没看到你破坏了 observable,works 数组在服务中,服务没有被破坏。所以它保留了数据。有三种方法可以解决这个问题

  1. 组件销毁时清空works数组

  2. 在组件的提供程序数组中包含服务,以便服务实例随组件销毁。

    @Component({providers:[WorkServices]})
    
  3. 每次调用 getWorks 时重新初始化工作数组。

解决方案完全取决于您的用例。理想情况下,在您遇到特定情况之前,不应在服务中管理阵列。

显然,结果缓存在您的服务中的 works 数组中。如果不需要这种行为,那么您可以简单地从服务中删除 works 属性 并从 getWorks 方法中删除它的使用:

getWorks() {
  return this.http.get(this.URL).pipe(
    map((resp: any) => resp.map((w: workModel) =>
      new workModel(
        w.description,
        w.client,
        w.employees,
        w.materials,
        w.isFinished,
        w.cost,
        w.id
      ))
    )
  );
}