Angular 如何从缓存的可观察数组中找到单个项
在过去的几天里,我一直在努力解决这个问题,但我一直运气不佳 这就是我要做的 我的网站对项目列表发出http get请求,并使用ngFor循环在主页上显示这些项目。我在Observable上使用shareReplay缓存这些结果,这样当我查看单个项目时,我就不需要再执行另一个网络请求 我的问题是,我找不到一种方法来从缓存后的观察值数组中提取单个项。我知道.find或.filter,但它们似乎是在最初获取可观察对象时使用的,而不是在使用shareReplay缓存后使用的 下面是我的代码Angular 如何从缓存的可观察数组中找到单个项,angular,rxjs,Angular,Rxjs,在过去的几天里,我一直在努力解决这个问题,但我一直运气不佳 这就是我要做的 我的网站对项目列表发出http get请求,并使用ngFor循环在主页上显示这些项目。我在Observable上使用shareReplay缓存这些结果,这样当我查看单个项目时,我就不需要再执行另一个网络请求 我的问题是,我找不到一种方法来从缓存后的观察值数组中提取单个项。我知道.find或.filter,但它们似乎是在最初获取可观察对象时使用的,而不是在使用shareReplay缓存后使用的 下面是我的代码 //
//service.ts
get allProjects() {
if (!this.cache$) {
this.cache$ = this.fetchProjects().pipe(shareReplay(1));
}
return this.cache$;
}
fetchProjects() {
return this.http
.get<Project[]>(
'https://admin.steezy.io/wp-json/wp/v2/posts?categories=5'
)
.pipe(
map((projects) => {
return projects.map((item) => {
return new Project(
item.id,
item.slug,
item.title,
item.content,
item.better_featured_image,
new Acf(
item.acf.projectDescription,
item.acf.projectTypeOfWork,
item.acf.sliderLinks
)
);
});
}),
);
}
// component.ts
ngOnInit(): void {
const slug = this.route.snapshot.params['slug'];
this.project = this.projectService.singleProject;
return this.project;
}
但它告诉我,属性“find”在类型“Observable”上不存在。
我试过了。过滤器和我得到了同样的问题
这似乎是件很容易的事,但不知为什么我被难住了。我已经缓存了数据,我所需要做的就是根据slug从中选择一个对象
有什么想法吗
编辑: 我根据阿德里安的回答解决了这个问题。现在我的IDE中出现了一个小错误
<div class="container" *ngIf="project$ | async as project">
<div class="row my-5">
<div class="col-sm-12 text-center">
<h1>
<!-- {{ project$ | async | json }} -->
{{ project.title.rendered }}
//project.model.ts
export class Project {
constructor(
public id: number,
public slug: string,
public title: Title,
public content: string,
public better_featured_image: string,
public acf: Acf
) {}
}
export class Title {
constructor(public rendered: string) {}
}
export class Acf {
constructor(
public projectDescription: string,
public projectTypeOfWork: string,
public sliderLinks: any = null
) {}
}
{{project.title.rendered}
//project.model.ts
出口类项目{
建造师(
公众id:号码,
公共slug:string,
公开名称:名称,
公共内容:字符串,
公共更好的功能图片:字符串,
公共机场核心设施:机场核心设施
) {}
}
导出类标题{
构造函数(公共呈现:字符串){}
}
出口级Acf{
建造师(
公共项目说明:字符串,
公共项目工作类型:字符串,
公共滑块链接:any=null
) {}
}
标题
以红色下划线,我的ide给出的错误是标识符“title”未定义null'不包含此类成员
知道为什么吗?用管道将可观察到的东西穿过地图
this.project$ = this.projectService.cache$.pipe(
map(projects => projects.find(project => project.slug == slug))
);
请注意,project$是可观察的,而不是项目对象。您需要使用异步管道将其展开或订阅
像打开一样打开它
<ng-container *ngIf="project$ | async as project">
{{ project | json }}
</ng-container>
{{project | json}}
谢谢您的回答。我马上就试了,但没有成功。我在控制台中遇到此错误,无法访问属性“rendered”,ctx.project$。标题未定义。当您说使用异步管道展开时,您的意思是像这样的{{project$.title.rendered | async}
project$是可观察的而不是项目对象。在模板中尝试{{project$|async | json}
,查看您的编辑是否有效!非常感谢你。我现在收到一个小错误,请检查我原来的帖子-我做了编辑。再次感谢你。我在这上面花了很多时间。请确保cache$现在键入为Observable
,它键入为cache$:Observable代码>删除[]会导致一个错误我是说项目数组显示项目的类定义?你是说项目模型吗?如果是这样,我用它编辑了我的作品。
<ng-container *ngIf="project$ | async as project">
{{ project | json }}
</ng-container>