Angular Signal 不断从 RxJs Observable 返回空数组

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

使用 Angulars toSignal 函数时,我不断得到一个空数组。

observable 返回一个包含 5 个对象的数组。

但是信号返回一个空数组。

下面是服务代码和组件代码。

API服务

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

@Injectable({
  providedIn: 'root'
})
export class SpringAPIService {

  private readonly baseUrl = 'http://localhost:8080';

  http = inject(HttpClient)

  getData(endpoint: string): Observable<any> {
    const url = `${this.baseUrl}/${endpoint}`;
    const headers = new HttpHeaders().set('Content-Type', 'application/json');
    const observable = this.http.get(url, { headers });
    return observable;
  }

}

Angular 17 组件

import { Component, Injector, Signal, inject, runInInjectionContext, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SpringAPIService } from '../spring-api.service';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-projects',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './projects.component.html',
  styleUrl: './projects.component.scss'
})
export class ProjectsComponent {

  http: SpringAPIService = inject(SpringAPIService);
  injector = inject(Injector);
  data: Signal<any> = signal([])

  ngOnInit() {
    runInInjectionContext(this.injector, () => {
      this.data = toSignal(this.http.getData('projects'), { initialValue: [] });
      console.log(this.data())
    });
 
  }

}
angular rxjs signals
1个回答
0
投票

当您仅记录信号时,您将获得其当前值,在您的情况下为初始值

[]
,并且不会获得任何进一步的更新。

如果您想对信号变化做出反应,可以使用

effect
computed
或 HTML 绑定。这是
effect
的示例:

export class App {
  http: SpringAPIService = inject(SpringAPIService);
  data = toSignal(this.http.getData('users'), { initialValue: [] });

  constructor() {
    // if this is ran after HTTP request completes, you will get updated data (only once)
    // setTimeout(() => console.log('+++ DATA', this.data()), 2000);
    effect(() => {
      console.log('+++ DATA', this.data());
    });
  }
}

在这种情况下,您将获得 2 个日志:首先是初始数据,然后是获取的数据。

我创建了一个 STACKBLITZ 来演示它。

© www.soinside.com 2019 - 2024. All rights reserved.