GET有时我在处理请求时遇到一些问题Angular。我正在使用ReplaySubject并返回,Observable但有时在应用程序的重新加载中,get请求正在工作,但它正在获取null数据或消息No content,尽管有数据。经过 3-4 次尝试后,它会显示数据。该请求get有效,但有时为空,有时给我数据。有人可以帮我解决这个问题吗?如果有可能给出任何使用ReplaySubject或类似的想法,因为我需要每次重新加载页面以获取新数据。这是我的Frontend部分。export class ModelDataService { public baseUrl = environment.backend; private data = new ReplaySubject<any>(1); public userID = this.authService.userID; constructor(private http: HttpClient, private authService: AuthService) { } public getJSON() { return this.http.get(`${this.baseUrl}/data/${this.userID}`).subscribe(res => this.data.next(res)); } public dataModel(): Observable<any> { return this.data.asObservable(); } public setData(data: Model) { const api = `${this.baseUrl}/data`; const user_id = this.authService.userID; this.http.post(api, data, { headers: {user_id} }).subscribe(res => this.data.next(res)); } public updateDate(id: string, dataModel: Model) { const api = `${this.baseUrl}/data/${id}`; return this.http.put(api, dataModel).subscribe(res => res); }}这是component我得到的数据 ngOnInit() { this.authService.getUserProfile(this.userID).subscribe((res) => { this.currentUser = res.msg; }); this.modelDataService.getJSON(); this.model$ = this.modelDataService.dataModel(); this.model$.subscribe((test) => { this.model = test; }); this.model$.subscribe((test) => { this.model = test; }); }这就是这backend部分。const ModelData = require("../models/data");async show(req, res) {let modelData;await ModelData.findOne({user: req.params.id}, (error, user) => { modelData = user;}); if (!modelData) { res.status(204).json({error: "No Data"}); return; }return res.status(200).send(modelData);},routes.get("/data/:id", ModelDataController.show);routes.post("/data", ModelDataController.store);routes.put("/data/:id", ModelDataController.update);
1 回答
狐的传说
TA贡献1804条经验 获得超3个赞
如果传入回调函数,Mongoose 将异步执行查询并将结果传递给回调。有时您无法获取数据是因为查询尚未执行完毕。要解决此问题,您可以将代码更改为:
let modelData = await ModelData.findOne({user: req.params.id}); if (!modelData)...
添加回答
举报
0/150
提交
取消