使用BehaviourSubject检索数据

时间:2019-02-17 10:48:55

标签: angular

我正在尝试通过BehaviourSubject检索我的数据,但是我没有得到预期的输出(因为behaviourSubject仅发出最后一个值,但在这里我得到了意外的输出

在第一个提交表单上,我在控制台中获得一个输出,第二个我在控制台中获得两个输出,类似地,在第三个表单上,我获得3个输出,依此类推 下面是我的代码 意外的输出显示在这里

https://ibb.co/pfBdXJ7

<div class="row">
<div class="col-md-5">
<form (ngSubmit)="onsubmit()" #f="ngForm">
<div class="md-form form-group mt-5">
<input mdbInput type="text" class="form-control" 
id="formGroupExampleInputMD" placeholder="Title"
ngModel name="title" required #title="ngModel"
>
</div>

<div class="md-form form-group mt-5">
<input mdbInput type="text" class="form-control" 
id="formGroupExampleInput2MD" placeholder="Price"
ngModel name="price" required #price="ngModel">
</div>

<div class="md-form form-group mt-5">
<select class="browser-default custom-select" name="select" 
required ngModel #select="ngModel" [ngModel]="default">
  <option value="Bread" >Bread</option>
  <option value="Dairy">Dairy</option>
  <option value="Fruits">Fruits</option>
  <option value="Seasonings and Spices">Seasonings and 
Spices</option>
  <option value="Vegetables">Vegetables</option>
</select>

<div class="md-form form-group mt-5">
  <input mdbInput type="text" class="form-control" 
id="formGroupExampleInput2MD" placeholder="imageurl"
  ngModel name="imageurl" required #imageurl="ngModel"
  >
</div>
</div>

 <button type="submit" mdbBtn color="primary" 
 mdbWavesEffect>Save</button>

</form>

</div>


<div class="col-md-6">
 <router-outlet></router-outlet>

</div>
</div>

.component ts

export class NewproductsComponent implements OnInit {
@ViewChild('f') form:NgForm
default="Bread"
constructor(private prservice:ProductService,private 
router:Router,private route:ActivatedRoute) { 
 }

ngOnInit() {

 }
onsubmit(){

let items=this.form.value
this.prservice.productslist.next(items)
this.prservice.addtocards(items)
this.router.navigate(['card'],{relativeTo:this.route})


} 

}

服务文件

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';




@Injectable({
providedIn: 'root'
})
export class ProductService {

productslist=new BehaviorSubject<any>(1)
cards:any[]=[]

constructor() { 


}


addtocards(values){
values.id=this.cards.length
this.cards.push(values)
// console.log(this.cards)
}




}

我订阅的组件

export class NewcardComponent implements OnInit {
subscription:Subscription
cardvalues
constructor(private prservice:ProductService) { }

ngOnInit() {
this.subscription=this.prservice.productslist.subscribe(
  (item)=>{
    this.cardvalues=item
    console.log(this.cardvalues)


  }
)
}

}

0 个答案:

没有答案