Angular - 对 rxResource() 中的变化做出反应

问题描述 投票:0回答:1

当 rxResource 接收 .value() 而不是使用 Effect() 时,如何对更改做出反应/执行副作用?

组件中当前的方法:

  constructor() {
    this.service.setItemId(1); //setting signal
    effect(() => // work with data from async post request 
  } 

服务中:

 resource$ = rxResource({
    request: () => this.itemID$(), // signal 
    loader: ({ request: id }) => {
      return this.http.post('http://');
    }
  }); 
angular signals
1个回答
0
投票

您可以直接订阅资源的内部行为,并在

.value()
被访问或更新时执行副作用。这可以使反应性与组件的其余部分保持同步。

组件代码

import { Component, signal, effect, OnInit } from '@angular/core';
import { Service } from './service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  data: any; 
  private subscription: any; 
  
  constructor(private service: Service) {}

  ngOnInit(): void {
    this.service.setItemId(1);

    this.subscription = this.service.resource$.subscribe((result) => {
      this.data = result;
      console.log('Received data:', result);
      // Perform your side-effects here
    });
  }

  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

服务代码:

import { Injectable, signal } from '@angular/core';
import { rxResource } from '@angular/core/rxjs'; 
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class Service {
  private itemId = signal<number | null>(null);

  constructor(private http: HttpClient) {}

  setItemId(id: number): void {
    this.itemId.set(id); 
  }

  resource$ = rxResource({
    request: () => this.itemId(), 
    loader: ({ request: id }) => {
      if (id === null) {
        return null; 
      }
      return this.http.post(`http://example.com/api`, { id });
    },
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.