为什么这个变量返回 undefined 而不是我的 Angular 13 应用程序中的对象?

拉兹万赞菲尔

我正在开发一个电子商务应用程序,它的前端是用 Angular 13 制作的。

我使用服务来处理来自 API 的产品。我在响铃以显示产品详细信息时遇到问题

在此处查看Stackblitz演示

app\services\product.service.ts我有:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Product, ProductResponse } from '../models/product';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  products: Product[] = [];

  apiURL: string = 'https://dummyjson.com';

  constructor(private http: HttpClient) {}
  
  // Product List       
  public getProducts(): Observable<ProductResponse>{
    return this.http.get<ProductResponse>(`${this.apiURL}/products`);
  }

  // Product Details (single product)
  public getProductDetails(id: Number): Observable<ProductResponse>{
    return this.http.get<ProductResponse>(`${this.apiURL}/products/${id}`);
  }
}

app\app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { Routes, RouterModule } from '@angular/router';
import { NavbarComponent } from './components/navbar/navbar.component';
import { FooterComponent } from './components/footer/footer.component';
import { SidebarComponent } from './components/sidebar/sidebar.component';
import { HomeComponent } from './components/home/home.component';
import { ProductItemComponent } from './components/product-item/product-item.component';
import { ProductsListComponent } from './components/products-list/products-list.component';
import { ProductsDetailsComponent } from './components/products-details/products-details.component';

const routes: Routes = [
  { path: '', component:  HomeComponent},
  { path: 'products', component:  ProductsListComponent},
  { path: 'products/show/:id', component:  ProductsDetailsComponent},
];

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    SidebarComponent,
    ProductsListComponent,
    ProductItemComponent ,
    ProductsDetailsComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(routes),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app\models\product.ts

export class Product {
    id?: number;
    title?: string;
    description?: string;
    price?: number;
    discountPercentage?: number;
    rating?: number;
    stock?: number;
    brand?: string;
    category?: string;
    thumbnail?: string;
}

export interface ProductResponse {
    products: Product[];
    total: number;
    skip: number;
    limit: number;
}

app\components\products-details\products-details.component.ts我有:

import { Component, OnInit, InputDecorator, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Product, ProductResponse } from '../../models/product';
import { ProductService } from '../../services/product.service';

@Component({
  selector: 'app-products-details',
  templateUrl: './products-details.component.html',
  styleUrls: ['./products-details.component.css']
})
export class ProductsDetailsComponent implements OnInit {

  @Input() product!: Product;
  productResponse: any;

  constructor(private ProductService: ProductService, private Router: Router, private ActivatedRoute:ActivatedRoute) { }

  ngOnInit(): void {
    const id = Number(this.ActivatedRoute.snapshot.paramMap.get('id'));
    this.ProductService.getProductDetails(id).subscribe((response) => (this.productResponse = response));

  }
}

app\components\products-details\products-details.component.html我有:

<h1>{{ product.title }}</h1>

问题

当我访问产品详细信息路径(例如http://localhost:4200/products/show/1)时,页面显示一个空<h1>标签,Chrome 控制台显示Cannot read properties of undefined (reading 'title')

我的错误在哪里?

圣诞树

https://dummyjson.com/products端点不同,https://dummyjson.com/products/{id}返回一个普通Product对象,所以:

// product.service.ts
public getProductDetails(id: Number): Observable<Product>{
  return this.http.get<Product>(`${this.apiURL}/products/${id}`);
}

// products-details.component.ts
// the @Input decorator is wrong — the data is not passed to the component from outside
// but instead fetched inside of the component
@Input() product!: Product;
// productResponse: any — this field is unused and should be removed

ngOnInit(): void {
  ...
  this.ProductService.getProductDetails(id).subscribe((product) => (this.product = product));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我收到TypeError:undefined不是Angular中的对象(求值”)?

为什么我不能在这个 Angular 9 应用程序中将变量从组件传递到服务?

为什么我不能在我的节点应用程序中重命名这个对象?

为什么这个变量不是对象?

为什么我的 Angular 应用程序在我更改引导程序顺序时卡在加载中?

为什么这个变量的实际值没有被用作我试图返回的对象的索引号

在执行这个程序时,char 函数会返回变量。我不知道为什么?

为什么 RoutingModule 在我的 angular 应用程序中不起作用?

是什么导致此 Angular 13 应用程序中的“仅允许数组和可迭代”错误?

在iOS 13中,当用户在应用程序切换器中向上滑动我的应用程序时,会发生什么事件?

为什么我不能在我的 Angular 应用程序中将此用户对象设置为 null?

为什么我得到 undefined 不是 vue js 中的对象错误

从 angular13 中的服务中获取 UNDEFINED 值

为什么fetch返回我的React应用程序的index.html而不是我提供的URL?

在我的 Angular 应用程序中,这个 Firestore 时间戳到日期转换有什么问题?

如何在我的 Angular 应用程序中从数组内的对象中获取值

为什么Boxplot出现在RStudio中而不是我的Shiny应用程序中?

为什么这个程序的输出不是我的想法

为什么在我使用打字稿的 Angular 应用程序中,在这种情况下没有更改函数内的变量?

为什么我的这个opengl应用程序出现黑屏?

为什么这个抽屉会关闭我的应用程序?

为什么我的Thymeleaf视图HTML文件在Spting应用程序中不显示对象列表?

为什么我的 phonegap 应用程序中的导航器对象为空?

为什么我的JSON.stringify(value,replacer)中的replacer函数在Angular应用程序中不接收键?

为什么Angular $ resource返回Resource对象而不是class对象?

为什么“ undefined为null或不是对象”?

我想在我的Angular Web应用程序中使用Azure应用程序服务的``应用程序设置''变量

我什么时候应该直接在 Angular 应用程序中 DI 注入器?

express logger、morgan logger 等为什么我的服务器应用程序中需要这个?