无法从服务中获取 JSON 数据并显示在组件中。

huangapple go评论49阅读模式
英文:

Can't pull json data from service into component to display

问题

Here is the translated content from your provided code snippet:

新手入门Angular,我尝试按照教程操作。我通过HTTP调用将数据传入共享服务,但从那里似乎无法将其传递到我的组件中以在表格中显示。我可以在数据传入服务后记录数据,所以我知道拉取操作已经发生,但尽管在组件中设置了订阅,但那里的值仍然为undefined。我想我会先尝试映射一些字段,以确保它是否能正常工作,然后再创建其余部分... 有人知道我做错了什么吗?可能有很多问题:P

**IPix.ts**
```typescript
export interface IPix {
  legacyConfigTrackerId: number;
  contract: IContract;
  selected: boolean;
}

IContract.ts

export interface IContract {
    contractEffectiveDate: string;
}

pix-search.service.ts

@Injectable({
  providedIn: 'root',
})
export class PixSearchService {
  constructor(private http: HttpClient) {}

  pixUrl: string =
    'https://pix.example-dev.example.com/pix?startRow=0&endRow=1';

  getPixData(): Observable<IPix[]> {
    const headers = new HttpHeaders({
      'x-api-key':
        'ewogICAgImFwadgfdgUtleSIgOiAiMTIzIiWQiIDogIlBESSBEZXZlbgdgG9wZXIiCn0=',
    });

    return this.http
      .get<IPix[]>(this.pixUrl, {
        headers,
      })
      .pipe(
        tap((data) => console.log('All:', JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

  handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      errorMessage = `Server returned code:: ${err.status}, error message is: ${err.message}`;
    }

    console.error(errorMessage);
    return throwError(() => errorMessage);
  }
}

pix-table.component.ts

@Component({
  selector: 'pix-table-component',
  templateUrl: 'pix-table.component.html',
  styleUrls: ['pix-table.component.css'],
  providers: [PixSearchService, PixEditDialogComponent],
})
export class PixTableComponent implements IPix, IContract, OnInit, OnDestroy {
  // ... (the rest of your component code)
}

pix-table.component.html

<div kds-table-scroll [scrollType]="scrollType">
  <kds-table
    [size]="tableSize"
    [showHover]="showHover"
    [striped]="true"
    [sticky]="sticky"
  >
    <thead>
      <tr kds-table-row>
        <th kds-table-heading *ngFor="let col of columns">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr
        kds-table-row
        *ngFor="let row of pixRecords"
        [selected]="row.selected"
        (click)="open(row)"
      >
        <td kds-table-data>{{ row.legacyConfigTrackerId }}</td>
        <td kds-table-data>{{ row.contract.contractEffectiveDate }}</td>
      </tr>
    </tbody>
  </kds-table>
</div>

sample json payload

{
    "totalCount": 1,
    "results": [
        {
            "status": "Active",
            "claimType": "M",
            "payClass": "FLLBCORP",
            "noPayClassReason": "",
            "id": "5df4443a7eefff0710c04760",
            "legacyConfigTrackerId": "217",
            "rateEscalator": "No",
            "product": {
                "healthPlanCode": "FL",
                "orgType": "EX",
                "lineOfBusiness": "EX",
                "businessUnitCode": "EX",
                "programCode": "EX",
                "carrierCode": "EX",
                "network": "Example Network"
            },
            // (rest of the JSON content)
        }
    ]
}

Please note that I have translated the code parts you provided. If you need any specific explanations or further assistance, feel free to ask.

英文:

New to Angular and I'm trying to follow a tutorial. I'm pulling data into a shared service via an http call but from there I can't seem to get it into my component to be displayed in a table. I can log the data after it comes into the service so I know the pull is happening, but despite having set up a subscription in my component, the value there remains undefined. I thought I would just start with trying to map a few fields so that I can make sure it's working before I create the rest... Anyone know what I'm doing wrong? Probably a lot of things 无法从服务中获取 JSON 数据并显示在组件中。

IPix.ts

export interface IPix {
  legacyConfigTrackerId: number;
  contract: IContract;
  selected: boolean;
}

IContract.ts

export interface IContract {
    contractEffectiveDate: string;
}

pix-search.service.ts

@Injectable({
  providedIn: &#39;root&#39;,
})
export class PixSearchService {
  constructor(private http: HttpClient) {}

  pixUrl: string =
    &#39;https://pix.example-dev.example.com/pix?startRow=0&amp;endRow=1&#39;;

  getPixData(): Observable&lt;IPix[]&gt; {
    const headers = new HttpHeaders({
      &#39;x-api-key&#39;:
        &#39;ewogICAgImFwadgfdgUtleSIgOiAiMTIzIiWQiIDogIlBESSBEZXZlbgdgG9wZXIiCn0=&#39;,
    });

    return this.http
      .get&lt;IPix[]&gt;(this.pixUrl, {
        headers,
      })
      .pipe(
        tap((data) =&gt; console.log(&#39;All:&#39;, JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

  handleError(err: HttpErrorResponse) {
    let errorMessage = &#39;&#39;;
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      errorMessage = `Server returned code:: ${err.status}, error message is: ${err.message}`;
    }

    console.error(errorMessage);
    return throwError(() =&gt; errorMessage);
  }
}

pix-table.component.ts

@Component({
  selector: &#39;pix-table-component&#39;,
  templateUrl: &#39;pix-table.component.html&#39;,
  styleUrls: [&#39;pix-table.component.css&#39;],
  providers: [PixSearchService, PixEditDialogComponent],
})
export class PixTableComponent implements IPix, IContract, OnInit, OnDestroy {
  columns = [
    &#39;ID&#39;,
    &#39;Network&#39;,
    &#39;LOB&#39;,
    &#39;HP Code&#39;,
    &#39;Atypical&#39;,
    &#39;TIN&#39;,
    &#39;GNPI&#39;,
    &#39;Org&#39;,
    &#39;Business Unit Code&#39;,
    &#39;National Contract&#39;,
    &#39;National ContractType&#39;,
    &#39;Contract Type&#39;,
    &#39;Super Group&#39;,
    &#39;Contract Entity&#39;,
    &#39;Contract ID&#39;,
    &#39;Amendment ID&#39;,
    &#39;Contract Effective Date&#39;,
    &#39;Contract Termination Date&#39;,
  ];

  rows: any;
  tableSize: TableSize = &#39;small&#39;;
  showHover = true;
  sticky: TableStickyType = &#39;horizontal&#39;;
  scrollType: TableScrollType = &#39;both&#39;;
  label = &#39;Pix&#39;;
  disabled = &#39;disabled&#39;;
  error = &#39;error&#39;;
  maxlength = &#39;maxlength&#39;;
  showCounter = false;

  elevation: CardElevation = &#39;medium&#39;;

  subscription!: Subscription;

  legacyConfigTrackerId!: number;
  terminationDate!: string;
  recordId!: number;
  network!: string;
  lineOfBusiness!: string;
  healthPlanCode!: string;
  isAtypical!: string;
  tin!: string;
  groupNpi!: string;
  org!: string;
  businessUnitCode!: string;
  isNational!: string;
  nationalContractType!: string;
  contractType!: string;
  isSuperGroup!: string;
  contractEntity!: string;
  contractId!: string;
  amendmentId!: string;
  contractEffectiveDate!: string;
  effectiveDate!: string;
  contract!: IContract;
  selected: boolean = false;

  constructor(
    private pixSearchService: PixSearchService,
    private pixEditDialog: PixEditDialogComponent
  ) {}

  pixRecords: IPix[] = [];
  errorMessage: string = &#39;&#39;;

  ngOnInit(): void {
    this.subscription = this.pixSearchService.getPixData().subscribe({
      next: (pixRecords) =&gt; {
        this.pixRecords = pixRecords;
      },
      error: (err: string) =&gt; {
        this.errorMessage = err;
      },
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  open(row: any) {
    this.pixEditDialog.open(row);
  }
}

pix-table.component.html

&lt;div kds-table-scroll [scrollType]=&quot;scrollType&quot;&gt;
  &lt;kds-table
    [size]=&quot;tableSize&quot;
    [showHover]=&quot;showHover&quot;
    [striped]=&quot;true&quot;
    [sticky]=&quot;sticky&quot;
  &gt;
    &lt;thead&gt;
      &lt;tr kds-table-row&gt;
        &lt;th kds-table-heading *ngFor=&quot;let col of columns&quot;&gt;{{ col }}&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      &lt;tr
        kds-table-row
        *ngFor=&quot;let row of pixRecords&quot;
        [selected]=&quot;row.selected&quot;
        (click)=&quot;open(row)&quot;
      &gt;
        &lt;td kds-table-data&gt;{{ row.legacyConfigTrackerId }}&lt;/td&gt;
        &lt;td kds-table-data&gt;{{ row.contract.contractEffectiveDate }}&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/kds-table&gt;
&lt;/div&gt;

sample json payload

{
    &quot;totalCount&quot;: 1,
    &quot;results&quot;: [
        {
            &quot;status&quot;: &quot;Active&quot;,
            &quot;claimType&quot;: &quot;M&quot;,
            &quot;payClass&quot;: &quot;FLLBCORP&quot;,
            &quot;noPayClassReason&quot;: &quot;&quot;,
            &quot;id&quot;: &quot;5df4443a7eefff0710c04760&quot;,
            &quot;legacyConfigTrackerId&quot;: &quot;217&quot;,
            &quot;rateEscalator&quot;: &quot;No&quot;,
            &quot;product&quot;: {
                &quot;healthPlanCode&quot;: &quot;FL&quot;,
                &quot;orgType&quot;: &quot;EX&quot;,
                &quot;lineOfBusiness&quot;: &quot;EX&quot;,
                &quot;businessUnitCode&quot;: &quot;EX&quot;,
                &quot;programCode&quot;: &quot;EX&quot;,
                &quot;carrierCode&quot;: &quot;EX&quot;,
                &quot;network&quot;: &quot;Example Network&quot;
            },
            &quot;provider&quot;: {
                &quot;groupNpi&quot;: &quot;123456789&quot;,
                &quot;tin&quot;: &quot;123456789&quot;,
                &quot;isAtypical&quot;: &quot;No&quot;,
                &quot;superGroup&quot;: &quot;&quot;
            },
            &quot;contract&quot;: {
                &quot;type&quot;: &quot;Example&quot;,
                &quot;name&quot;: &quot;Example&quot;,
                &quot;emptorisNumber&quot;: &quot;47745&quot;,
                &quot;amendmentId&quot;: &quot;&quot;,
                &quot;pixContractType&quot;: &quot;Example&quot;,
                &quot;effectiveDate&quot;: &quot;07/01/2010&quot;,
                &quot;isStandard&quot;: &quot;Yes&quot;,
                &quot;isNational&quot;: &quot;Yes&quot;,
                &quot;isLessorOf&quot;: &quot;Yes&quot;,
                &quot;nuances&quot;: &quot;&quot;,
                &quot;isTimelyFiling&quot;: &quot;&quot;
            },
            &quot;changeRequest&quot;: {},
            &quot;capitation&quot;: {},
            &quot;audit&quot;: {
                &quot;createdBy&quot;: &quot;Developer&quot;,
                &quot;modifiedBy&quot;: &quot;Developer&quot;,
                &quot;validation&quot;: [],
                &quot;created&quot;: &quot;05/30/2013 08:31 AM CDT&quot;,
                &quot;modified&quot;: &quot;09/28/2021 10:44 AM CDT&quot;
            },
            &quot;hnetAudit&quot;: {
                &quot;dataValidationValue&quot;: &quot;&quot;
            },
            &quot;deleted&quot;: &quot;No&quot;
        }
    ]
}

答案1

得分: 1

The response shared is an object but not an array of IPix type. Believe that you need to get the results value from the response.

你分享的响应是一个对象,但不是 IPix 类型的数组。相信你需要从响应中获取 results 的值。

You can achieve this with map operator from rxjs.

你可以使用 rxjs 中的 map 操作符来实现这一点。

Your getPixData method should be as below:

你的 getPixData 方法应该如下所示:

import { map } from 'rxjs';

getPixData(): Observable<IPix[]> {
  ...

  return this.http
    .get<any>(this.pixUrl, {
      headers,
    })
    .pipe(
      tap((data) => console.log('All:', JSON.stringify(data))),
      map((data: any) => data.results as IPix[]),
      catchError(this.handleError)
    );
}
英文:

The response shared is an object but not an array of IPix type. Believe that you need to get the results value from the response.

You can achieve this with map operator from rxjs.

map((data: any) =&gt; data.results as IPix[])

Your getPixData method should be as below:

import { map } from &#39;rxjs&#39;;

getPixData(): Observable&lt;IPix[]&gt; {
  ...

  return this.http
    .get&lt;any&gt;(this.pixUrl, {
      headers,
    })
    .pipe(
      tap((data) =&gt; console.log(&#39;All:&#39;, JSON.stringify(data))),
      map((data: any) =&gt; data.results as IPix[])
      catchError(this.handleError)
    );
}

答案2

得分: 0

the response is different from interface IPix so it can't read.if you want start with trying to map a few fields you can try this.

export interface IPix {
totalCount: number;
}

the IPix.totalCount should map the totalCount inresponsive (=1)

英文:

the response is different from interface IPix so it can't read.if you want start with trying to map a few fields you can try this.

export interface IPix {
  totalCount: number;
}

the IPix.totalCount should map the totalCount inresponsive (=1)

huangapple
  • 本文由 发表于 2023年5月18日 07:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定