0

I am trying to bind nested json object in my angular application. Here

component.html file

    <div class="row">
  <ul class=" g-img col-md-3 col-sm-3 col-xs-12" *ngFor="let data of ruleTypeList">
    <li *ngFor="let group of data.AnalyticsGroup; let i = index">
      <div class="object-box noti-box col s s1 home-box" >
        <p>{{data.RuleName}}</p>
       
        <p>{{group.GroupName}}</p>
        <div>
          <p>Overall Count: {{getCount(group.Id)}}</p>
        </div>
      </div>

    </li>
  </ul>
</div>

I am getting repetative id's as shown here. Due to which i cannot get stable overall count. enter image description here

component.ts file

  getCount(id){
   this.service.postGroupInfo(grpId).subscribe((res: any)=>{
 const count = res.Count
 return count

})
    }

How can i do it???

1
  • it seems that getCount should be async and return a call for this.service.postGroupInfo(grpId) Commented Mar 23, 2021 at 10:07

1 Answer 1

1

I love using pipe for this kind of problem

get-count.pipe.ts

import { Pipe, PipeTransform } from '@angular/core'
import { Service } from 'yourPath'

@Pipe({
  name: 'getCount',
})
export class getCountPipe implements PipeTransform {
  constructor(private _service: Service) {}

  transform(grpId: any): Promise<any> {
    return new Promise((resolve) => {
    if(!grpId) resolve(?) // grpId wasn't given with

      this._service.postGroupInfo(grpId).subscribe((response) => {
        resolve(response.Count)
      },(error) => {
         resolve('?') // Something wrong happen
        },
      )
    })
  }
}

component.module.ts

@NgModule({
 declarations: [
    //...
    getCountPipe,
  ],
  // ...
})

component.html

<p>Overall Count: {{group.Id | getCount | async}}</p>
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think it's a good idea to have subscribe inside transform method as it may produce memory leak. I would eliminate promise and return of(null) or this._service.postGroupInfo(grpId)
@vitaliykotov I got your point and it's interesting. I'm wasn't aware of this possible memory leak. would you think returning resolve(await this._service.postGroupInfo(grpId)) could be an improovement ? Or is it better to subscribe to a pipe and unsebscribe it on delete? If neither of both are good, could you link me to a page that explaine the of(null)? I'll then update my answer
of(null) it's just an example of what could be returned on error or when grpId is not provided. of is rxjs operator that creates an observable with provided value. this._service.postGroupInfo also returns an observable, so we should return either of them and there is no need in promise. And don't subscribe to postGroupInfo(grpId), | async pipe does it for you and unsubscribes on destroy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.