gpt4 book ai didi

javascript - 参数更改 GET 请求后 Angular 重新获取数据

转载 作者:可可西里 更新时间:2023-11-01 16:39:57 25 4
gpt4 key购买 nike

参数更改后如何重新获取数据:通过单击 oglas/1 到 oglas/2,所以当输入 URL 然后单击 ENTER 时一切正常,但是当呈现 oglas/1 时单击 oglas/2 按钮时,URL 更改为 oglas/2 但数据来自 oglas/1?

TS

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Post } from "../post.model";
import { ServerService } from "../server.service";

@Component({
selector: "post",
templateUrl: "./post.component.html",
styleUrls: ["./post.component.css"]
})
export class PostComponent implements OnInit {
post: Post[];

constructor(
private route: ActivatedRoute,
private serverService: ServerService
) {}

ngOnInit(): void {
this.getPost();
}

getPost(): void {
const id = +this.route.snapshot.paramMap.get("id");
this.serverService.getPosts(id).subscribe(post => (this.post = post));
}
}

服务

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Post } from "./post.model";
import { User } from "./user.model";
import { Observable } from "rxjs";

@Injectable({ providedIn: "root" })
export class ServerService {
usersUrl = "http://localhost:3000/users";
postsUrl = "http://localhost:3000/posts";

constructor(private http: HttpClient) {}

getPosts(id: number | string): Observable<Post[]> {
const url = `${this.postsUrl}/${id}`;
return this.http.get<Post[]>(url);
}

getUser(id: number | string): Observable<User[]> {
const url = `${this.usersUrl}/${id}`;
return this.http.get<User[]>(url);
}
}

最佳答案

由于您正在对 ngOnInit() 中的数据进行 API 调用,因此在您的组件加载时请求的数据可能不可用。 Angular 可能会重复使用组件的相同实例,从而使 ngOnInit() 只被调用一次。

您可以使用 Angular Resolver 来确保在加载组件之前拥有所需的数据。

1) 创建路由解析器以在加载路由之前获取所需的数据。

PostDataResolver.ts:

// ... imports

@Injectable()
export class PostDataResolver implements Resolve<any> {

constructor(private serverService: ServerService) {}

resolve(route: ActivatedRouteSnapshot) {

const id = route.paramMap.get('id');

return this.serverService.getPosts(id);
}
}

2) 将此解析器添加到您的路由模块:

{ path: "oglas/:id", component: PostComponent, resolve: { postData: PostDataResolver }}

3) 然后在你的组件中访问解析后的数据。

PostComponent.ts:

export class PostComponent implements OnInit {
post: Post[];

constructor(
private route: ActivatedRoute,
private serverService: ServerService
) {}

ngOnInit(): void {
this.post = this.route.snapshot.data.postData;
}
}

这可确保您在加载组件之前拥有最新且适当的数据。

关于javascript - 参数更改 GET 请求后 Angular 重新获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56265269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com