通过服务从一个组件到另一个组件获取数据并在html组件中呈现

时间:2019-02-22 09:34:52

标签: angular

我正在尝试从admin-new.component.ts到admin-card.component.ts ........提取数据。问题是我可以在控制台中看到我的数据,但是当我尝试在引导卡内的HTML组件中呈现它失败

这是屏幕截图的链接

https://ibb.co/5vsBvZs

admin-new.component.ts

export class AdminNewComponent implements OnInit {
   @ViewChild('f') form:NgForm
   categories
   default="Bread"
   constructor(public iservice:ItemsService,private 
   prservice:ProductsService,private router:Router,private 
   route:ActivatedRoute) { }

   ngOnInit() {
      this.iservice.getitems().subscribe(items=>{
      console.log(items)
      this.categories=items
      })
    }
    onsubmit(f){
       //console.log(f)

       this.prservice.fetchintocardcomponent(f)
       this.router.navigate(['admin/products/new/card'])
     }

 }

products.service.ts

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

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

cardsdatails:any[]=[]

   constructor() { }

   fetchproducts=new BehaviorSubject<any>(1);

   fetchintocardcomponent(data){
      this.cardsdatails.push(data);
      this.fetchproducts.next(this.cardsdatails.slice());
   }

}

admin-card.component.ts

export class AdminCardComponent implements OnInit {

   subscription:Subscription
   pvalue

   constructor(private prservice:ProductsService,private 
   route:ActivatedRoute,private router:Router) { }

   ngOnInit() {
      this.subscription=this.prservice.fetchproducts.subscribe((data=>{
      this.pvalue=data
      console.log(this.pvalue) //here i m seeing the output in the 
      }))

   }

 }

未呈现数据的html组件

 <mdb-card>
   <div class="view rgba-white-slight waves-light" mdbWavesEffect>
     <mdb-card-img src="{{pvalue?.imageurl}}" alt="Card image cap"></mdb- 
       card-img>
     <a>
      <div class="mask"></div>
     </a>
   </div>
   <mdb-card-body>
     <mdb-card-title>
       <h4>{{pvalue.title}}</h4>
     </mdb-card-title>

     <mdb-card-text> 
       {{pvalue.price}}
     </mdb-card-text>

   </mdb-card-body>
 </mdb-card>

1 个答案:

答案 0 :(得分:0)

pvalue是一个数组(从console.log(this.pvalue)看)。因此,您需要遍历它(使用* ngFor)或获取它的第一个元素(如果您只想这样做):

<mdb-card>
  <div class="view rgba-white-slight waves-light" mdbWavesEffect>
    <mdb-card-img src="{{pvalue[0]?.imageurl}}" alt="Card image cap"></mdb-card-img>
    <a>
      <div class="mask"></div>
    </a>
  </div>
  <mdb-card-body>
    <mdb-card-title>
      <h4>{{pvalue[0]?.title}}</h4>
    </mdb-card-title>
    <mdb-card-text> 
      {{pvalue[0]?.price}}
    </mdb-card-text>
  </mdb-card-body>
</mdb-card>