mongoose 更改路由后从MongoDB订阅API错误

mzsu5hc0  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(132)

我创建了一个服务来从MongoDB API获取数据。起初,它工作得很好。但是当我改变到另一个路由并返回时。它变得未定义。我点击浏览器刷新,它恢复正常。
product.service.ts:

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Observable, catchError, retry, throwError, map } from 'rxjs';
    import { Product } from '../interface/product';
    
    @Injectable({
        providedIn: 'root'
    })
    export class productAPIService {
    
        constructor(private _http: HttpClient) { }
    
        getProducts(category: string): Observable<any> {
            const headers = new HttpHeaders().set("Content-Type", "text/plain;charset=utf-8")
            const requestOptions: Object = {
                headers: headers,
                responseType: "text"
            }
            return this._http.get<any>("http://localhost:3002/" + category, requestOptions).pipe(
                map(res => JSON.parse(res) as Array<Product>),
                retry(3),
                catchError(this.handleError)
            )
        }
        
        track_products(category: string){
            let products_lst: any;
            this.getProducts(category).subscribe(res => {
                products_lst = res;
            });
            return products_lst;
        }
    
        handleError(error: HttpErrorResponse) {
            return throwError(() => new Error(error.message))
        }
    
    }

字符串
product-list.component.ts:

import { CommonModule } from '@angular/common';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { productAPIService } from '../../services/product.service';
import {NgxPaginationModule} from 'ngx-pagination';

@Component({
  selector: 'app-product-list',
  standalone: true,
  imports: [CommonModule, NgxPaginationModule],
  templateUrl: './product-list.component.html',
  styleUrl: './product-list.component.css'
})
export class ProductListComponent implements OnInit, OnDestroy{
  p: number = 1;
  all_products: any = [];
  daychuyen_products: any = [];
  nhan_products: any = [];
  vongtay_products: any = [];
  bongtai_products: any = [];
  fil_products: any = [];

  constructor(private _service: productAPIService) { }

  ngOnInit(): void {
    this.daychuyen_products = this._service.track_products("daychuyen");
    this.nhan_products = this._service.track_products("nhan");
    this.vongtay_products = this._service.track_products("vongtay");
    this.bongtai_products = this._service.track_products("bongtai");

    this.all_products = [].concat(this.bongtai_products, this.nhan_products, this. vongtay_products, this.daychuyen_products).sort(() => Math.random() - 0.5);
    this.fil_products = this.all_products;
    console.log(this.fil_products);
  }

  filledStars(num: number) {
    return Array(num).fill(0).map((x, i) => i + 1);
  }
  ngOnDestroy(): void {}
}


ng serve第一次时,按预期工作:x1c 0d1x
转到另一个工艺路线并返回到产品列表组件工艺路线:



有谁能为我解释一下。非常感谢!!!

kokeuurv

kokeuurv1#

当你的应用程序启动时,可能需要一些时间来呈现html。如果你构建的服务在获取数据方面更快,它会在html中正确显示所有数据,因为products数组没有未定义。
试着把“?.”在你的product-list.component.html中的第127行,就在你调用图像之前。这应该让渲染引擎知道页面第一次绘制的值可以是未定义的。Angular将处理传入的更新,并在异步请求完成后在屏幕上绘制所有数据。

相关问题