我一直在尝试在我的视图中显示从文件上传的数据。根据我在Angular文档和在线中所读到的内容,使用更改检测应该是我在更新数据时如何完成刷新页面的部分并且该更改未反映在我的视图中。
我使用的界面在translations.ts中定义我的数据:
export interface ITranslation {
siteName: string;
pageName: string;
languageCode: string;
englishCaption: string;
translatedCaption: string;
arrayIndex?: number;
}
我正在使用此类型的脚本代码来执行导入和html模板以显示它:
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ROUTER_DIRECTIVES, CanDeactivate, ComponentInstruction, Router } from '@angular/router-deprecated';
import { ITranslation } from './translation';
declare var Papa: any;
@Component({
templateUrl: 'app/translator-page-data-import.component.html',
styleUrls: ['app/translator-page-data-import.component.css',
'app/assets/css/ngmes.css',
'app/assets/css/toastr.min.css',
'app/assets/css/ui-grid.min.css',
'app/assets/css/ui-grid-override.css'],
directives: [ROUTER_DIRECTIVES],
selector:'table',
changeDetection: ChangeDetectionStrategy.Default
})
export class TranslatorPageDataImportComponent implements OnInit {
pageTitle: string = 'Page Data Import';
hasData: boolean = false;
translations: ITranslation[] = [{
"siteName": "none",
"pageName": "none",
"languageCode": "none",
"englishCaption": "none",
"translatedCaption": "none"
}];
constructor(private router: Router) {
}
onChanges(changes){
console.log("onChanges was fired");
}
ngOnInit(): void {
console.log('PAGE "' + this.pageTitle + '" WAS LOADED!!!');
}
importFile(evt) {
let fileInput = evt.target;
let file = fileInput.files[0];
let textType = /text.*/;
if (file.type.match(textType)) {
let reader = new FileReader();
reader.onload = function(e) {
let incomingCsvData: string = reader.result;
// turn on if you need to inspect the raw CSV data
// console.log("Incoming CSV Data" + incomingCsvData);
let newJsonData: any = Papa.parse(incomingCsvData, {header: true});
// turn on if you need to see the converted CSV data
//console.log("Incoming CSV Data converted to JSON: ");
//console.log(JSON.stringify(newJsonData));
if (newJsonData.errors.length == 0 ) {
this.translations = newJsonData.data;
console.log("Translations data was populated from file: ")
console.log(JSON.stringify(this.translations));
for (var i = 0; i < this.translations.length; i++) {
this.translations.arrayIndex = i;
}
this.translations.push({
"siteName": "none",
"pageName": "none",
"languageCode": "none",
"englishCaption": "none",
"translatedCaption": "none"
});
this.hasData = true;
console.log("hasData is " + this.hasData);
}
else {
for (var i = 0; i < newJsonData.errors.length; i++) {
console.log("There were errors Importing the data.");
console.log("Error Type: " + newJsonData[i].errors.type);
console.log("Error Code: " + newJsonData[i].errors.code);
console.log("Error Message: " + newJsonData[i].errors.message);
console.log("Error Row: " + newJsonData[i].errors.row);
}
}
}
reader.readAsText(file);
} else {
console.log("File not supported!");
}
}
}
&#13;
<div class='container-fluid'>
<div class="page-title">
<h3>{{pageTitle}}</h3>
</div>
<div class='page-body'>
<div class='row'>
<div class="form-group required">
<div class='col-md-3'>
<input type="file" id="fileInput" (change)='importFile($event)'>
</div>
<div class='col-md-3'>
</div>
<div class='col-md-3'>
</div>
<div class='col-md-3'>
</div>
</div>
</div>
<div class='row'>
<div class='col-xs-12' id="newTranslationsRow">
<div [ngSwitch]="hasData">
<div *ngSwitchWhen="true">
<h1>Data was imported</h1>
</div>
<div *ngSwitchWhen="false">
<h1>No data was imported</h1>
</div>
<div *ngSwitchDefault>
<h1>No data was imported</h1>
</div>
</div>
<div class='table-responsive' id="translationsTable" *ngIf='translations && translations.length'>
<table class='table'>
<thead>
<tr>
<th>Application Name</th>
<th>Page Name</th>
<th>Language-Country Code</th>
<th>English Caption</th>
<th>Translated Caption</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let translation of translations'>
<td>{{ translation.siteName }}</td>
<td>{{ translation.pageName }}</td>
<td>{{ translation.languageCode }}</td>
<td>{{ translation.englishCaption }}</td>
<td>{{ translation.translatedCaption }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
&#13;
这是我的控制台日志输出,显示基础JSON数据数组中的数据:
Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
translator-page-data-import.component.ts:43 PAGE "Page Data Import" WAS LOADED!!!
translator-page-data-import.component.ts:95 Translations data was populated from file:
translator-page-data-import.component.ts:96 [{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Active","translatedCaption":"Active","arrayIndex":"0"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Add","translatedCaption":"Add","arrayIndex":"1"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Cancel","translatedCaption":"Cancel","arrayIndex":"2"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Delete","translatedCaption":"Delete","arrayIndex":"3"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Load","translatedCaption":"Load","arrayIndex":"4"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Okay","translatedCaption":"Okay","arrayIndex":"5"},{"siteName":"ct","pageName":"setup","languageCode":"en-US","englishCaption":"Save","translatedCaption":"Save","arrayIndex":"6"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Active","translatedCaption":"Activo","arrayIndex":"7"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Add","translatedCaption":"A?adir","arrayIndex":"8"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Cancel","translatedCaption":"Cancelar","arrayIndex":"9"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Delete","translatedCaption":"Borrar","arrayIndex":"10"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Load","translatedCaption":"Carga","arrayIndex":"11"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Okay","translatedCaption":"Bueno","arrayIndex":"12"},{"siteName":"ct","pageName":"setup","languageCode":"es-MX","englishCaption":"Save","translatedCaption":"Salvar","arrayIndex":"13"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Active","translatedCaption":"Aktiv","arrayIndex":"14"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Add","translatedCaption":"Hinzuf?gen","arrayIndex":"15"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Cancel","translatedCaption":"Stornieren","arrayIndex":"16"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Delete","translatedCaption":"L?schen","arrayIndex":"17"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Load","translatedCaption":"Belastung","arrayIndex":"18"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Okay","translatedCaption":"Okay","arrayIndex":"19"},{"siteName":"ct","pageName":"setup","languageCode":"de-DE","englishCaption":"Save","translatedCaption":"sparen","arrayIndex":"20"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Active","translatedCaption":"Active","arrayIndex":"21"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Add","translatedCaption":"Add","arrayIndex":"22"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Cancel","translatedCaption":"Cancel","arrayIndex":"23"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Delete","translatedCaption":"Delete","arrayIndex":"24"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Load","translatedCaption":"Load","arrayIndex":"25"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Okay","translatedCaption":"Okay","arrayIndex":"26"},{"siteName":"ct","pageName":"AppCommon","languageCode":"en-US","englishCaption":"Save","translatedCaption":"Save","arrayIndex":"27"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Active","translatedCaption":"Activo","arrayIndex":"28"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Add","translatedCaption":"A?adir","arrayIndex":"29"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Cancel","translatedCaption":"Cancelar","arrayIndex":"30"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Delete","translatedCaption":"Borrar","arrayIndex":"31"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Load","translatedCaption":"Carga","arrayIndex":"32"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Okay","translatedCaption":"Bueno","arrayIndex":"33"},{"siteName":"ct","pageName":"AppCommon","languageCode":"es-MX","englishCaption":"Save","translatedCaption":"Salvar","arrayIndex":"34"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Active","translatedCaption":"Aktiv","arrayIndex":"35"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Add","translatedCaption":"Hinzuf?gen","arrayIndex":"36"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Cancel","translatedCaption":"Stornieren","arrayIndex":"37"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Delete","translatedCaption":"L?schen","arrayIndex":"38"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Load","translatedCaption":"Belastung","arrayIndex":"39"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Okay","translatedCaption":"Okay","arrayIndex":"40"},{"siteName":"ct","pageName":"AppCommon","languageCode":"de-DE","englishCaption":"Save","translatedCaption":"sparen","arrayIndex":"41"}]
translator-page-data-import.component.ts:111 hasData is true
我在这个主题上尝试了很多变化(即使用各种变化检测方法,使用自定义HTML标签,使用Angular 2 ngSwitches&amp; ngIfs等等),但没有运气。 我也试过直接访问HTML元素来操作它以使其显示(即blur()和focus()等...)没有运气。
我可能不正确地进行Angular 2变化检测,但没有一步一步的例子解释究竟如何&amp;为什么每一步都完成了我所见过的。
任何帮助将不胜感激。
谢谢, 比尔
答案 0 :(得分:0)
可能还有其他事情,但首先切换到使用箭头功能来保留this
的范围
更改
reader.onload = function(e) {
到
reader.onload = (e) => {
答案 1 :(得分:0)
所以,我找到了我的问题的答案。 我需要的是一个简单的服务来获取我的数据。数据更改时,视图将更新。
以下是我所做的总结:
我添加了一个简单的服务(TranslatorDataImportService),如下所示:
import { Injectable } from '@angular/core';
import { ITranslation } from './translation';
@Injectable()
export class TranslatorDataImportService {
// the default state before translations are imported
noTranslations: ITranslation[] = [{
"appName": "none",
"pageName": "none",
"cultureInfo": "none",
"target": "none",
"value": "none"
}];
importedTranslations: ITranslation[];
getImportedTranslatorData(newTranslations?: ITranslation[]) {
if (newTranslations) {
this.importedTranslations = newTranslations;
}
else {
this.importedTranslations = this.noTranslations;
}
return Promise.resolve(this.importedTranslations);
}
}
然后我修改了原始类型的脚本文件,如下所示:
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ROUTER_DIRECTIVES, CanDeactivate, ComponentInstruction, Router } from '@angular/router-deprecated';
import { ITranslation } from './translation';
import { TranslatorDataImportService } from './translator-data-import.service';
import { TranslatorService } from './translator.service';
declare var Papa: any;
@Component({
templateUrl: 'app/translator-page-data-import.component.html',
styleUrls: ['app/translator-page-data-import.component.css',
'app/assets/css/ngmes.css',
'app/assets/css/toastr.min.css',
'app/assets/css/ui-grid.min.css',
'app/assets/css/ui-grid-override.css'],
directives: [ROUTER_DIRECTIVES],
selector:'table',
changeDetection: ChangeDetectionStrategy.Default
})
export class TranslatorPageDataImportComponent implements OnInit {
pageTitle: string = 'Import Application Data';
hasData: boolean = false;
errorMessage: string;
importErrorMessage: string;
translations: ITranslation[];
constructor(private _translatorService: TranslatorService,
private _translatorDataImportService: TranslatorDataImportService,
private router: Router) {
}
getTranslations(importedTranslations?: ITranslation[]): void {
this._translatorDataImportService.getImportedTranslatorData(importedTranslations).then(translations => this.translations = translations);
}
ngOnInit(): void {
console.log('PAGE "' + this.pageTitle + '" WAS LOADED!!!');
this.getTranslations();
}
saveTranslations(applicationName: string, importedData: ITranslation[]): void {
this._translatorService.saveTranslations(applicationName, importedData)
.subscribe(
error => this.errorMessage = <any>error);
if (this.errorMessage) {
console.log("An error occured saving the data: " + this.errorMessage);
}
console.log("Save call complete");
}
onChanges(changes){
console.log("onChanges was fired");
}
importFile(evt) {
this.hasData = true;
console.log("hasData is " + this.hasData);
let fileInput = evt.target;
let file = fileInput.files[0];
let textType = /text.*/;
if (file.type.match(textType)) {
let reader = new FileReader();
reader.onload = (e) => {
let incomingCsvData: string = reader.result;
// turn on if you need to inspect the raw CSV data
// console.log("Incoming CSV Data" + incomingCsvData);
let newJsonData: any = Papa.parse(incomingCsvData, {header: true});
// turn on if you need to see the converted CSV data
// console.log("Incoming CSV Data converted to JSON: ");
// console.log(JSON.stringify(newJsonData));
if (newJsonData.errors.length == 0 ) {
let importedTranslations: ITranslation[] = newJsonData.data;
let applicationName: string;
let passedTranslations: ITranslation[]= [];
let ignoredTranslations: ITranslation[]= [];
let index: number = 0;
console.log("Translations data was populated from file: ")
console.log(JSON.stringify(importedTranslations));
if (importedTranslations.length > 0) {
applicationName = importedTranslations[0].appName;
console.log("Application Name = " + applicationName);
}
for (var i = 0; i < importedTranslations.length; i++) {
importedTranslations[i].arrayIndex = i;
}
this.getTranslations(importedTranslations);
// this.saveTranslations(applicationName,importedTranslations);
}
else {
for (var i = 0; i < newJsonData.errors.length; i++) {
console.log("There were errors Importing the data.");
console.log("Error Type: " + newJsonData[i].errors.type);
console.log("Error Code: " + newJsonData[i].errors.code);
console.log("Error Message: " + newJsonData[i].errors.message);
console.log("Error Row: " + newJsonData[i].errors.row);
}
}
}
reader.readAsText(file);
} else {
console.log("File not supported!");
}
}
}
即使我将数据传递给&#34;获取数据的服务,即
this.getTranslations(importedTranslations);
从我读过的内容来看,这显然是谷歌希望你做的,而不是我在做什么。
希望这有助于其他人在类似问题上挣扎。