TypeScript报错:Cannot read property 'toString' of null 问题求助
Hey there! It sounds like your issue is definitely tied to the product_id not being properly passed or initialized when you reuse the Active component inside the Product component. Let's break down some practical fixes:
1. Explicitly Pass product_id via Input Binding
First, make sure your Active component is set up to accept the product ID from its parent (the Product component):
In active.ts, add an @Input() property to receive the ID:
import { Input } from '@angular/core'; // ... other imports and component decorator export class ActiveComponent { @Input() productId: string | number; // Define the input property activateProduct() { // Your existing activation logic here } }
Then in Product.html, pass the product ID when using the Active component:
<!-- Replace currentProduct.id with your actual product ID variable from the Product component --> <app-active [productId]="currentProduct.id"></app-active>
Double-check that currentProduct in the Product component is initialized before the Active component renders—if it's loaded asynchronously (like from an API), you might need to wait for it to exist.
2. Add Null Checks in Your Activation Function
Prevent the toString() call from running if productId is null/undefined by adding a guard clause:
In active.ts:
activateProduct() { // Exit early if productId is missing if (!this.productId) { console.warn('Product ID is missing—cannot activate product'); return; } // Safe to call toString() now const productIdStr = this.productId.toString(); // Rest of your activation logic... }
3. Conditionally Render the Slide Toggle
You can also avoid rendering the slide toggle altogether until the productId is available. In active.html:
<mat-slide-toggle *ngIf="productId" (change)="activateProduct()"> Toggle Product Activation </mat-slide-toggle>
This way, the toggle won't exist until the ID is ready, so there's no chance of triggering the function with a null ID.
4. Use Optional Chaining for Template Expressions
If you're using productId.toString() directly in your template, use the optional chain operator (?.) to safely access the method:
<!-- Example of using optional chaining in the template --> <div>Current Product ID: {{ productId?.toString() }}</div>
This will return undefined instead of throwing an error when productId is null.
Any of these approaches should resolve the "Cannot read property 'toString' of null" error. Start with checking that the productId is being passed correctly from the Product component, since that's the most common culprit when reusing components.
内容的提问来源于stack exchange,提问作者A. B

