Angular 21将 Observable转换为Signal时不起作用
我正在用Angular版本21开发一个Angular项目,但数据未能从Web API加载到应用中(Web API正在正常工作)。以下是加载数据的代码:
export class ProductcategoryService {
Productcategories:Subject<IProductCategory[]> = new Subject<IProductCategory[]>();
constructor(private httpClient:HttpClient)
{
}
GetAllProductCategories() : Observable<IProductCategory[]>{
let getcategoriesUrl = global.serverBase + "/api/ProductCategories/GetAllProductCategories";
return this.httpClient.get<IProductCategory[]>(getcategoriesUrl,{ withCredentials: true });
}
}
这是用于加载数据的UI代码:
productCategories = signal<IProductCategory[]>([]);
constructor(private productcategoryservice: ProductcategoryService,public authService:AuthService,private title:Title)
{
this.productcategoryservice.GetAllProductCategories().subscribe(
(data: IProductCategory[]) => {
this.productCategories.set(data);
}
);
}
在浏览器开发者工具的控制台标签页中,显示出如下警告列表:
数据未加载的原因是什么?
解决方案
请通过以下方式再次检查你的HttpClient:
GetAllProductCategories() : Observable<IProductCategory[]>{
let getcategoriesUrl = global.serverBase + "/api/ProductCategories/GetAllProductCategories";
return this.httpClient.get<IProductCategory[]>(getcategoriesUrl,{ withCredentials: true });
.pipe(
tap(res=> console.log(res))
)
}
}
很可能是后端返回的数据在转换阶段不正确,或者与你的接口定义不匹配。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。
