我有Angular的HTML页面:
<div class="example-container mat-elevation-z8">
<div class="example-loading-shade"
*ngIf="isLoadingResults">
<mat-spinner *ngIf="isLoadingResults"></mat-spinner>
</div>
<div class="button-row">
<a mat-flat-button color="primary" [routerLink]="['/products']"><mat-icon>list</mat-icon></a>
</div>
<mat-card class="example-card">
<mat-card-header>
<mat-card-title><h2>{{product.prod_name}}</h2></mat-card-title>
<mat-card-subtitle>{{product.prod_desc}}</mat-card-subtitle>
</mat-card-header>
<mat-card-content>
<dl>
<dt>Product Price:</dt>
<dd>{{product.prod_price}}</dd>
<dt>Updated At:</dt>
<dd>{{product.updated_at | date}}</dd>
</dl>
</mat-card-content>
<mat-card-actions>
<a mat-flat-button color="primary" (click)="editProduct()"><mat-icon>edit</mat-icon></a>
<a mat-flat-button color="warn" (click)="deleteProduct(product.id)"><mat-icon>delete</mat-icon></a>
</mat-card-actions>
</mat-card>
</div>
及其对应的组件类:
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {ApiService} from '../api.service';
import {Product} from '../product';
import {ViewProductService} from '../view-product.service';
import {Subscription} from 'rxjs/internal/Subscription';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.sass']
})
export class ProductDetailComponent implements OnInit, OnDestroy {
product = {} as Product;
product2 = {} as Product;
subscription: Subscription;
isLoadingResults = true;
constructor(private route: ActivatedRoute, private api: ApiService, private router: Router, private viewProductService: ViewProductService) {
}
ngOnInit(): void {
this.subscription = this.viewProductService.getCurrentProduct().subscribe(value => {
this.product.id = String(value['_id']);
this.product.prod_name = value.prod_name;
this.product.prod_desc = value.prod_desc;
this.product.prod_price = value.prod_price;
});
this.isLoadingResults = false;
// this.getProductDetails(this.route.snapshot.params['id']);
}
getProductDetails(id) {
this.api.getProduct(id)
.subscribe(data => {
this.product = data;
this.product.id = id;
console.log(this.product);
this.isLoadingResults = false;
});
}
editProduct() {
this.viewProductService.viewProduct(this.product);
this.router.navigate(['/product-edit']);
}
deleteProduct(id) {
this.isLoadingResults = true;
this.api.deleteProduct(id)
.subscribe(res => {
this.isLoadingResults = false;
this.router.navigate(['/products']);
}, (err) => {
console.log(err);
this.isLoadingResults = false;
}
);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
我是Angular的新手,这也许是一个新手。我的问题是调用onclick事件时,总是在ngOnInit
方法之前调用editProduct
方法。
对吗?对我来说,这是一个意想不到的行为。我不需要再次调用ngOnInit
方法,因为它可以再次呈现页面,而我不需要。
存在一种不会在每次调用editProduct方法时都调用ngOnInit的方法吗?