我有两个组件,第一个叫做 product
,第二个叫做 product-details
.
我想点击 product
导航到`product-details``组件(两个组件不显示在同一页面中) .
我创建了一个名为 sessionService
的服务来传递这两个组件之间的数据 . 我查看了多个解决方案,并尝试了这个:
How to share data between components using a service properly?但它不起作用 .
Here is session service:
import { Injectable } from '@angular/core';
import {IProduct} from "./product";
import { BehaviorSubject} from "rxjs/internal/BehaviorSubject";
@Injectable({
providedIn: 'root'
})
export class SessionService {
private product = new BehaviorSubject<IProduct>({name:'asd',id:3,image:"asas",price:"asd"});
currentProduct = this.product.asObservable();
changeProduct(product:IProduct){
console.log("shit");
this.product.next(product);
}
constructor() {}
}
And here is product component:
import {Component, Input, OnInit} from '@angular/core';
import {IProduct} from "../product";
import {SessionService} from "../session.service";
@Component({
selector: 'ec-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {
@Input() product:IProduct;
@Input() productShape:string;
constructor(private sessionService:SessionService) { }
ngOnInit() {
}
goToProductDetails(){
window.location.href = "product";
this.sessionService.changeProduct(this.product);
}
}
And here is product template:
<div class="prod-ver" *ngIf="productShape==='vertical'" (click)="goToProductDetails()">
<figure class="fig-ver"><img [src]="product.image" alt="product"></figure>
<div class="p-name">{{product.name}}</div>
<div class="p-price">{{product.price}}</div>
</div>
product details component:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {IProduct} from "../product";
import {SessionService} from "../session.service";
@Component({
selector: 'ec-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
productId:number;
products:IProduct[];
product:IProduct;
constructor(private route:ActivatedRoute,private sessionService:SessionService) { }
ngOnInit() {
this.sessionService.currentProduct.subscribe(
product => {
this.product = product;
console.log(this.product);
}
);
}
}
}
1 回答
作为最佳实践,我会将产品的ID与请求一起传递到详细信息页面,然后使用resolver加载产品 .
或者,我建议使用角度路由器而不是
window.location.href = "product";
这样页面将不会刷新,并且存储在服务中的状态应该保持不变 . 确保将import { AppRoutingModule } from './app-routing.module';
包含到app.module.ts中 .