打字稿响应选择数据

时间:2020-06-19 18:41:17

标签: javascript angular asp.net-mvc typescript

HMy html显示未定义(未定义),我可以在调试器中看到数据,所以我不确定是否未正确使用选择数据? HTML视图

<div *ngIf="publishItemsWarningMessage" class="text-danger">
    {{publishItemsWarningMessage}}
    <ul>
        <li *ngFor="let detail of publishItemsWarningMessageDetails">
            {{detail}}
        </li>
    </ul>
</div>

打字稿

if (response.UnpublishedRelatedTemplates.length > 0) {
    this.publishItemsWarningMessageDetails = Enumerable
        .From(response.UnpublishedRelatedTemplates)
        .Select(UnpublishedRelatedTemplates => response.UnpublishedRelatedTemplates.RelatedTemplateId + " (" + response.UnpublishedRelatedTemplates.TemplateId + ")")
        .ToArray();
}

调试

enter image description here

UI显示未定义(未定义)

enter image description here

1 个答案:

答案 0 :(得分:2)

如下更新您的Typescript代码。将response.UnpublishedRelatedTemplates内的UnpublishedRelatedTemplates替换为.Select(...)

if (response.UnpublishedRelatedTemplates.length > 0) {
    this.publishItemsWarningMessageDetails = Enumerable
        .From(response.UnpublishedRelatedTemplates)
        .Select(UnpublishedRelatedTemplates => UnpublishedRelatedTemplates.RelatedTemplateId + " (" + UnpublishedRelatedTemplates.TemplateId + ")")
        .ToArray();
}

说明 之所以会得到undefined,是因为在Select内部您正在使用response.UnpublishedRelatedTemplates.RelatedTemplateId,但是response.UnpublishedRelatedTemplatesarray,因此它不会有RelatedTemplateId。相反,您可以使用index [index]来获得response.UnpublishedRelatedTemplates[index].RelatedTemplateId之类的价值。

但是由于您已经在阵列上Enumerating,所以UnpublishedRelatedTemplates将拥有response.UnpublishedRelatedTemplates[index]的值。因此,您只需替换它即可。

在下面尝试

let response = {
  UnpublishedRelatedTemplates: [{
    RelatedTemplateId: 'TMRelated2',
    TemplateId: 'TMRelated1'
  }, {
    RelatedTemplateId: 'TMDummy2',
    TemplateId: 'TMDummy1'
  }]
};

if (response.UnpublishedRelatedTemplates.length > 0) {
  let publishItemsWarningMessageDetails = Enumerable
    .From(response.UnpublishedRelatedTemplates)
    .Select(UnpublishedRelatedTemplates => UnpublishedRelatedTemplates.RelatedTemplateId + " (" + UnpublishedRelatedTemplates.TemplateId + ")")
    .ToArray();

  console.log(publishItemsWarningMessageDetails);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js" integrity="sha256-dq1fzSor46Oc+U/DjuE2hKKN0FfvbVx+CW5GBn1mhiQ=" crossorigin="anonymous"></script>