- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试在 Angular 2 中创建一个组件来显示来自服务的数据。该服务基本上是在用户输入一些内容后从 json 文件加载一些数据。我一直在尝试让组件更新,但它似乎无法识别更改,除非我在从我的服务提交事件后调用 zone.run() 。我的组件代码如下...
@Component({
selector: 'assess-asset-group',
directives: [AssetComponent, AssetHeaderComponent, NgFor, NgIf],
template: `
<div *ngIf="assetService.schema != null">
<div class="asset-group" *ngFor="#assetTypeName of assetService.schema.assetTypeNames">
<div class="asset-type-title"><span>{{assetService.schema.assetTypes[assetTypeName].name}}s</span></div>
<table class="asset-group-table" cellpadding=0 cellspacing=0>
<thead>
<tr assess-asset-header [assetType]="assetService.schema.assetTypes[assetTypeName]"></tr>
</thead>
<tbody>
<tr assess-asset *ngFor="#asset of assetService.assetsForType(assetTypeName)" [asset]="asset"></tr>
</tbody>
</table>
<button class="new-asset-btn" (click)="assetService.addAsset(assetTypeName)">New</button>
</div>
</div>`,
providers: [provide(AssetService, {useValue: injector.get(AssetService)})]
})
export class AssetGroupComponent {
public assetService: AssetService;
public zone: NgZone;
constructor( @Inject(AssetService) assetService: AssetService, zone: NgZone) {
this.assetService = assetService;
this.zone = zone;
}
ngOnInit() {
this.assetService.proejectLoadedEmitter.subscribe((e) => { this.zone.run(() => { }) });
}
ngOnDestroy() {
this.assetService.proejectLoadedEmitter.unsubscribe();
}
}
我是不是做错了什么或者这是我需要做的来更新 View ?
更新 - Assets 服务类
@Injectable()
export class AssetService{
public assets: Assets.Asset[] = [];
public assetTypeDefinitions: any = null;
public schema: Schema = null;
public assetsAsObj: any = null; // Asset file loaded as object
@Output() proejectLoadedEmitter: EventEmitter<any> = new EventEmitter();
constructor(){
}
public loadProject(config: Project){
// Load schema
// populate AssetTypeDefinitions as object keyed by type
let data = fs.readFileSync(config.schemaPath, 'utf8');
if (!data) {
utils.logError("Error reading schema file");
return;
}
let struc = fs.readFileSync(config.structurePath, 'utf8');
if (!struc) {
utils.logError("Error reading structure file");
return;
}
this.schema = new Schema(JSON.parse(data), struc);
this.readAssets(config.assetFilePath);
}
/**
* @brief Adds a new asset to the assets array
* @details Constructs the asset based on the type and populates
* its fields with appropreiate default values
*
* @param type The type of the asset - specified in the schema
*/
public addAsset(type: string): void {
// Need to make sure there is a loaded type definition for the specified type
if(!this.schema.assetTypes.hasOwnProperty(type)){
utils.logError("Error occured during call to addAsset - type \"" + type + "\" is not specified in the loaded schema");
return;
}
// Creeate a new asset object - passing in the type definition from the schema
this.assets.push(new Assets.Asset(this.schema.assetTypes[type]));
}
/**
* Write the current assets to a file using the specified format
* If the outputPasth isn't specied try and load it from the project.json file
*/
public writeAssets(format:AssetWriteFormat, outputPath?: string) : void {
var outStructureStr = this.schema.structureStr;
// insert AS properties from schema into output assets
this.schema.properties.forEach(prop => {
outStructureStr = outStructureStr.replace(new RegExp('"' + prop +'"', 'i'), this.retriveValueForSchemaProperty(prop));
});
fs.writeFileSync("C:/Projects/Assess/assets.json", outStructureStr);
}
public readAssets(inputPath?: string) : void{
let assetsStr = fs.readFileSync(inputPath, 'utf8');
let strucToAssetMap = {};
let strucObj = JSON.parse(this.schema.structureStr);
this.schema.properties.forEach(p => {
strucToAssetMap[p] = this.findValueInObject(strucObj, p).reverse();
});
// @TODO Load custom properties
let assetsObj = JSON.parse(assetsStr);
var c = null;
strucToAssetMap["AS_ASSETS"].forEach(p => {
if(c == null){
c = assetsObj[p];
}else{
c = c[p];
}
});
c.forEach((asset) => {
let a:Assets.Asset = new Assets.Asset(this.schema.assetTypes[asset.type], asset);
this.assets.push(a);
});
console.log(this.assets);
this.proejectLoadedEmitter.emit(null);
}
public assetsForType(type:string): Assets.Asset[]{
var ret: Assets.Asset[] = [];
for(let idx in this.assets){
if(this.assets[idx].definition.type === type){
ret.push(this.assets[idx]);
}
}
return ret;
}
public retriveValueForSchemaProperty(property: string) : string{
if(AS_SchemaTypes.indexOf(property) != -1){
switch (property) {
case "AS_ASSETS":
let outAssets = [];
this.assets.forEach((asset) => {
let outAsset = {};
outAsset["type"] = asset.definition.type;
for (let key in asset.fields) {
outAsset[key] = asset.fields[key].value;
}
outAssets.push(outAsset);
});
return JSON.stringify(outAssets, null, "\t");
}
}else{
// @TODO Retrive custom properties
return '"DDDDDD"';
}
return "";
}
public findValueInObject(obj: any, property: string, path: any[] = []): any[] {
for(let x in obj){;
let val = obj[x];
if (val == property){
path.push(x);
return path;
}
else if(val != null && typeof val == 'object'){
let v = this.findValueInObject(val, property, path);
if(v != null){
path.push(x);
return path;
}
}
}
return null;
}
}
最佳答案
这需要了解您正在使用的 AssetService
的内部工作原理。
Angular 在大多数异步 API(addEventListener
, setTimeout
, ...)被修补的区域中运行你的组件的代码,这样区域可以在这样的时候通知 Angular发生了异步回调。这是 Angular 运行变更检测的时候。
如果你在 Angular 之外初始化 AssetService
或者 AssetService
通过其他方式在 Angulars 区域之外执行代码,那么 Angular 不会收到关于发生的异步回调的通知并且不会运行变化检测。
使用 zone.run(...)
,您可以明确地让代码在 Angulars 区域内执行,然后再运行更改检测。
关于typescript - Angular 2 - 为什么我需要 zone.run()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37148813/
在类中实现 NSCopying 的此方法以启用复制时,区域参数使用什么?如果我设置一个新对象,我不需要用 allocWithZone 来分配它,因为 alloc 就足够了......我很困惑.....
本文整理了Java中io.sphere.sdk.zones.Zone.getLocations()方法的一些代码示例,展示了Zone.getLocations()的具体用法。这些代码示例主要来源于Gi
本文整理了Java中io.sphere.sdk.zones.Zone.getId()方法的一些代码示例,展示了Zone.getId()的具体用法。这些代码示例主要来源于Github/Stackover
本文整理了Java中io.sphere.sdk.zones.Zone.referenceTypeId()方法的一些代码示例,展示了Zone.referenceTypeId()的具体用法。这些代码示例主
本文整理了Java中io.kaif.model.zone.Zone.valueOf()方法的一些代码示例,展示了Zone.valueOf()的具体用法。这些代码示例主要来源于Github/Stacko
本文整理了Java中io.kaif.model.zone.Zone.tryFallback()方法的一些代码示例,展示了Zone.tryFallback()的具体用法。这些代码示例主要来源于Githu
我的数据库中恰好有包含 timestamp without time zone 列的表。现在我需要根据时区比较它们。 我可以这样做: select my_timestamp::timestamp wi
我正在尝试 Angular 2。但是在将 zone.js 作为全局变量导入后出现此错误: 我的包及其版本: "dependencies": { "angular2": "2.0.0-beta.
可能我问这个问题已经太晚了,但无论如何。 有人可以解释一下在什么情况下我需要导入区域的补丁 - zone.js/dist/zone-patch-rxjs。据我所知,补丁已添加到此 PR 中(this
问题很简短:如果我已经在没有时区的时间戳类型的列中有数据,如果我将类型设置为带时区的时间戳,postgresql 将如何处理这些数据? 最佳答案 它将当前值保留在本地时间并将时区设置为本地时间的偏移量
我有一个在东部时区的时间,但我想将它调整为中部时区。两个时区都在美国。我从来没有这样做过?我不知道如何转换它。请帮帮我好吗? 最佳答案 这是一种可能的方法: $dt = new DateTime('2
我在 Angular 11 上有一个应用程序刚刚开始在所有浏览器、所有环境(本地/暂存/生产)上同时出现错误(大约一个小时前,没有任何更新或任何东西): Uncaught TypeError: t.g
我们有一个函数,可以像 JS 一样解析 UTC 中的日期/时间对,但随后强制它的行为就像在本地时区中指定的一样。如下: var tz = (new Date()).toString().match(/
我很难理解 "AT TIME ZONE 'localtime'" 究竟是如何工作的?通过使用它,我发现它的行为与 "AT TIME ZONE 'UTC'" 完全一样......但是为什么呢? "loc
我在 PostgreSQL 9.3 ALTER TABLE manual page 中找到了这个 ALTER COLUMN 语句: ALTER TABLE audits ALTER COLUM
首先,我意识到不推荐使用 time with time zone。我要使用它是因为我将多个 time with time zone 值与我当前的系统时间进行比较,而不管是哪一天。 IE。用户说每天 0
在 Rails 控制台中: > ActiveSupport::TimeZone['Samoa'].utc_offset => -39600 > ActiveSupport::TimeZone['Sam
我在两个不同的数据库中运行了相同的语句:我的本地数据库和 Oracle Live SQL . CREATE TABLE test( timestamp TIMESTAMP DEFAULT SY
我在两个不同的数据库中运行了相同的语句:我的本地数据库和 Oracle Live SQL . CREATE TABLE test( timestamp TIMESTAMP DEFAULT SY
在 Rails 3.0.10 中,我使用 Time.zone 来更改用户查看美国各地发布的类(class)时间的方式。然而,更改时区似乎并不像我期望的那样 Time.zone = TZInfo::Ti
我是一名优秀的程序员,十分优秀!