Я новичок в angular, и я разбираю JSON на DOM-элементы.
Часть ответа JSON:
"fabricAnswers": [
{
"id": 11,
"answer": "daily active users",
"answerValue": 7,
"platform": "android",
"syncTime": 1525096804000,
"appId": 5
},
{
"id": 12,
"answer": "daily new users",
"answerValue": 1,
"platform": "android",
"syncTime": 1525096804000,
"appId": 5
},
{
"id": 13,
"answer": "monthly active users",
"answerValue": 272,
"platform": "android",
"syncTime": 1525096804000,
"appId": 5
},
{
"id": 14,
"answer": "crash-free users",
"answerValue": 100,
"platform": "android",
"syncTime": 1525096804000,
"appId": 5
},
{
"id": 15,
"answer": "sessions",
"answerValue": 9,
"platform": "android",
"syncTime": 1525096804000,
"appId": 5
},
{
"id": 16,
"answer": "daily active users",
"answerValue": 10,
"platform": "ios",
"syncTime": 1525096805000,
"appId": 5
},
{
"id": 17,
"answer": "daily new users",
"answerValue": 4,
"platform": "ios",
"syncTime": 1525096805000,
"appId": 5
},
{
"id": 18,
"answer": "monthly active users",
"answerValue": 480,
"platform": "ios",
"syncTime": 1525096805000,
"appId": 5
},
{
"id": 19,
"answer": "crash-free users",
"answerValue": 100,
"platform": "ios",
"syncTime": 1525096805000,
"appId": 5
},
{
"id": 20,
"answer": "sessions",
"answerValue": 11,
"platform": "ios",
"syncTime": 1525096805000,
"appId": 5
}
]
И я просматриваю JSON с помощью этого HTML-кода;
<div class = "row ">
<div class = "col-xs-12 col-sm-3" *ngFor = "let statistic of statistic.statistics">
<div class = "block">
<div class='block-body'> {{ statistic.appName }} </div>
<table>
<tr>
<th>Syncdate</th>
<th><img src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Android_robot.svg/2000px-Android_robot.svg.png" alt = "" border=3 height=30 width=25></th>
<th><img src = "https://cayland.com/images/ios-logo.png" alt = "" border=3 height=30 width=60></th>
</tr>
<tr *ngFor = "let info of statistic.fabricAnswers">
<td *ngIf = "info.platform == 'android'"> {{info.answer}}</td>
<td *ngIf = "info.platform == 'android'"> {{info.answerValue}}</td>
<td *ngIf = "info.platform == 'ios'">{{info.answerValue}}</td>
</tr>
</table>
</div>
</div>
Как видите, детали iOS представлены ниже. Это происходит из-за того, что <td *ngIf = "info.platform == 'ios'">{{info.answerValue}}</td>
пуст при разборе элементов «Android». Как мне заполнить пустую колонку данными iOS?
Обновлено: Я реализовал то, что сказал Паркар:
Component.HTML:
<div class = "row ">
<div class = "col-xs-12 col-sm-3" *ngFor = "let statistic of statistic.statistics">
<div class = "block">
<div class='block-body'> {{ statistic.appName }} </div>
<table>
<tr>
<th>Syncdate</th>
<th><img src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Android_robot.svg/2000px-Android_robot.svg.png" alt = "" border=3 height=30 width=25></th>
<th><img src = "https://cayland.com/images/ios-logo.png" alt = "" border=3 height=30 width=60></th>
</tr>
<tr *ngFor = "let info of statistic.fabricAnswers">
<td *ngIf = "info.platform == 'android'"> {{info.answer}}</td>
<td *ngIf = "info.platform == 'android'"> {{info.answerValue}}</td>
<!--<td *ngIf = "info.platform == 'ios'">{{info.answerValue}}</td>-->
<td>{{getIphoneValue(statistic.fabricAnswers, info)}}</td>
</tr>
</table>
</div>
</div>
component.ts:
export class StatisticsComponent implements OnInit {
constructor(private statistic: HttpclientService) { }
ngOnInit() {}
getIphoneValue(list: any[], info: any) {
return list.find(i =>
i.answer === info.answer && i.platform === 'ios'
).answerValue;
}
}
Я получаю сообщение об ошибке:
ERROR TypeError: Cannot read property 'answerValue' of undefined
at StatisticsComponent.getIphoneValue (statistics.component.ts:18)
at Object.eval [as updateRenderer] (StatisticsComponent.html:16)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735)
at checkAndUpdateView (core.js:13849)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
at callViewAction (core.js:14195)
at execEmbeddedViewsAction (core.js:14153)
at checkAndUpdateView (core.js:13845)
Только покажите ответ платформы android
и возьмите ответы на вопросы платформы ios
через function
или, возможно, вы можете написать Pure Pipe (более производительный).
<ng-container *ngFor = "let info of fabricAnswers">
<tr *ngIf = "info.platform == 'android'">
<td *ngIf = "info.platform == 'android'"> {{info.answer}}</td>
<td *ngIf = "info.platform == 'android'"> {{info.answerValue}}</td>
<td>{{getIphoneValue(fabricAnswers, info)}}</td>
</tr>
</ng-container>
Код
getIphoneValue(list: any[],info: any) {
var iosItem = list
.find(i =>
i.answer == info.answer && i.platform === 'ios'
);
return iosItem ? iosItem.answerValue: '';
}
@jozofe, вам нужно настроить имена переменных, например, здесь я использовал разные, чтобы демонстрация работала и была более понятной
да я именно твой код скопировал. Но в функции getIphoneValue () после answerValue говорится: «Отсутствует точка с запятой». Я использую другую версию angular?
Добавьте точку с запятой после answerValue
Не уверен, что случилось. Но я уверен, что это не имеет отношения к версиям Angular.
Я получаю сообщение «Контекст ошибки» в строке <td> {{getIphoneValue (statistic.fabricAnswers, info)}} </td>
Вы добавили функцию в текущий компонент шаблона?
Подскажите одну вещь, возможно ли, что не могло быть ответа ios
, вроде как здесь происходит ..
теперь появляется еще одна ошибка: «TypeError: невозможно прочитать свойство« найти »из неопределенного»
Я исправил проблему с помощью трубы:
export class IospipePipe implements PipeTransform {
transform(value: any[], info: any): any {
for (const i of value) {
if (i.answer === info.answer && i.platform === 'ios') {
return i.answerValue;
}
}
return null;
}
}
спасибо за ваш ответ, но я получаю эту ошибку: ERROR TypeError: Невозможно прочитать свойство answerValue of undefined в StatisticsComponent.getIphoneValue (statistics.component.ts: 21) в Object.eval [as updateRenderer] (StatisticsComponent.html: 16) в Object.debugUpdateRenderer [как updateRenderer] (core.js: 14735)