Angular 5仅ng serve --prod时报错:Property 'id'不存在于ProductModel
Let's break down your issue and answer your questions step by step:
Why does ng serve work but ng serve --prod throw an error?
The core difference here is that Angular's production mode enables strict template type checking by default, while development mode uses more lenient checks (or skips some entirely). Here's what's likely going on:
- Your
ProductModeldefinition is missing theidproperty (or has a case mismatch likeIdinstead ofid). Even if the API returns anidfield, TypeScript can't validate it against your model if the model doesn't explicitly declare it. - The data returned from
bcProductService.getProductByIdisn't properly typed. If your service method doesn't specify it returns aProductModel, TypeScript might infer a generic type that excludesid—development mode overlooks this, but prod mode's strict checks catch it. - You're assigning
single.datatoproductwithout type validation. Ifsingle.data's structure doesn't matchProductModel, loose development checks let it slide, but strict prod checks flag the mismatch when the template tries to accessproduct.id.
Answers to your questions
1. Did I set this.product incorrectly?
Your assignment logic is fine, but there's a type mismatch issue. Fix these points to resolve the error:
- Verify your
ProductModel: Make sure it explicitly includes theidproperty. For example:export interface ProductModel { id: number; // or string, match your API's data type // add other product properties here } - Type your service response: Ensure
getProductByIdreturns an Observable of the correct type, so TypeScript knowssingle.datais aProductModel:
This tells TypeScript exactly what structure to expect from the API response, making the assignmentgetProductById(id: number): Observable<{ data: ProductModel }> { return this.http.get<{ data: ProductModel }>(`your-api-url/${id}`); }this.product = single.datatype-safe.
2. How can I see all errors in development mode?
You don't need to rely solely on ng build --prod to catch these issues. Enable strict checks in your project so development mode flags the same errors as prod:
Open your
tsconfig.jsonfile and update these settings:{ "compilerOptions": { "strict": true, // Enables all strict type-checking options "noImplicitAny": true // Flags variables with implicit `any` type }, "angularCompilerOptions": { "strictTemplates": true // Enables strict template type checking (prod default) } }After saving, run
ng serve—you'll now see the sameidproperty error in development mode, letting you fix it early.About
environment.ts: Enabling strict checks doesn't affect your environment variables at all. You can still useenvironment.prod.tsfor production-specific configs while keeping strict checks enabled in both modes. Strict checks only enforce type safety, which is independent of your environment setup.
内容的提问来源于stack exchange,提问作者Omar

