我试图使用服务通过Subject传递数据,但是我第一次在控制台中看不到任何内容,但是我单击了Edit按钮,但是当我第二次单击按钮时,我看到了结果 当我发出admin products.component.ts
中的值时this.prservice.editproduct.next(this.editedproduct)
在这里工作正常,问题在于我想订阅的同时,这也是我第一次点击
admin-products.component.html
<button type="button" [routerLink]="['new']" mdbBtn color="primary"
mdbWavesEffect>New Product</button>
< table mdbTable>
<thead>
<tr>
<th *ngFor="let head of headElements" scope="col">{{head}} </th>
</tr>
</thead>
<tbody>
<tr mdbTableCol *ngFor="let item of listofproducts;let id=index"
>
<th>{{id}}</th>
<th scope="row">{{item.title}}</th>
<td>{{item.price}}</td>
<td (click)="onclickedit(id)" class="edititem">Edit</td>
</tr>
</tbody>
</table>
admin-products.components.ts
import { Component, OnInit } from '@angular/core';
import { Productservice } from 'src/app/services/products.service';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-admin-products',
templateUrl: './admin-products.component.html',
styleUrls: ['./admin-products.component.scss']
})
export class AdminProductsComponent implements OnInit {
listofproducts
editedproduct
constructor(private prservice:Productservice,private
router:Router,private route:ActivatedRoute) {
}
ngOnInit() {
this.listofproducts=this.prservice.getallproducts()
}
headElements = ['Title', 'Price'];
onclickedit(id){
this.editedproduct=this.prservice.getspecificproduct(id)
this.prservice.editproduct.next(this.editedproduct)
this.router.navigate(['edit',id],{relativeTo:this.route})
}
}
所以我试图将经过编辑的产品传递给这里的另一个组件
Products.service.ts
import { Subject } from "rxjs";
export class Productservice{
productcard=new Subject<any>()
editproduct=new Subject<any>()
cards:any[]=[]
addtocardarray(value){
this.cards.push(value)
// console.log(this.cards)
}
getallproducts(){
return this.cards
}
getspecificproduct(id){
return this.cards[id]
}
}
edit-products.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Productservice } from 'src/app/services/products.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-edit-products',
templateUrl: './edit-products.component.html',
styleUrls: ['./edit-products.component.scss']
})
export class EditProductsComponent implements OnInit {
id:number
editproductdetails
subscription:Subscription
constructor(private prservice:Productservice,private
router:Router,private route:ActivatedRoute) { }
ngOnInit() {
// console.log(this.id)
this.route.params.subscribe(
(params)=>{
this.id=+params['id']
console.log(this.id)
}
)
this.subscription=this.prservice.editproduct.subscribe(
(values)=>{
console.log(values)
this.editproductdetails=values
console.log(this.editproductdetails)
}
)
}
}
所以在这里,当我尝试控制台日志值或this.editproductsdetals时,控制台中什么都看不到
答案 0 :(得分:0)
然后,问题是在创建子组件之前,您将新值传递给主题。而且由于该子组件不知道“主题”更改,因为订阅后并未发生。
常规Subject
的工作原理如下。您必须先订阅主题,然后它才能产生新的价值,否则它将无法为您带来任何价值!
您应该使用BehaviorSubject
。此处的区别在于BehaviorSubject
始终拥有一个值。当有人订阅时。它将发出它持有的最后一个值。