无法将JSON数据从服务拉入组件中显示

z8dt9xmd  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(68)

我是Angular的新手,我正在尝试遵循教程。我通过一个http调用将数据拉入一个共享服务,但似乎无法将其放入我的组件并显示在一个表中。我可以在数据进入服务后记录数据,这样我就知道拉取正在发生,但是尽管在我的组件中设置了订阅,那里的值仍然是未定义的。我想我应该先尝试Map几个字段,这样我就可以确保它在创建其余字段之前正常工作。有人知道我哪里做错了吗?可能有很多东西:P

IPix.ts

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 {
  columns = [
    'ID',
    'Network',
    'LOB',
    'HP Code',
    'Atypical',
    'TIN',
    'GNPI',
    'Org',
    'Business Unit Code',
    'National Contract',
    'National ContractType',
    'Contract Type',
    'Super Group',
    'Contract Entity',
    'Contract ID',
    'Amendment ID',
    'Contract Effective Date',
    'Contract Termination Date',
  ];

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

  elevation: CardElevation = 'medium';

  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 = '';

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

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

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

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>

json负载示例

{
    "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"
            },
            "provider": {
                "groupNpi": "123456789",
                "tin": "123456789",
                "isAtypical": "No",
                "superGroup": ""
            },
            "contract": {
                "type": "Example",
                "name": "Example",
                "emptorisNumber": "47745",
                "amendmentId": "",
                "pixContractType": "Example",
                "effectiveDate": "07/01/2010",
                "isStandard": "Yes",
                "isNational": "Yes",
                "isLessorOf": "Yes",
                "nuances": "",
                "isTimelyFiling": ""
            },
            "changeRequest": {},
            "capitation": {},
            "audit": {
                "createdBy": "Developer",
                "modifiedBy": "Developer",
                "validation": [],
                "created": "05/30/2013 08:31 AM CDT",
                "modified": "09/28/2021 10:44 AM CDT"
            },
            "hnetAudit": {
                "dataValidationValue": ""
            },
            "deleted": "No"
        }
    ]
}
9njqaruj

9njqaruj1#

响应与接口IPix不同,所以它无法读取。如果你想开始尝试Map一些字段,你可以尝试这样做。

export interface IPix {
  totalCount: number;
}

IPix.totalCount应Map无响应的totalCount(=1)

k2arahey

k2arahey2#

共享的响应是一个对象,但不是IPix类型的数组。相信你需要从响应中得到results值。
您可以使用 rxjs 中的map运算符来实现这一点。

map((data: any) => data.results as IPix[])

你的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)
    );
}

相关问题