我想将组件中的数据共享到另一个文件中的其他组件。我创建了一个对象/类的数组,我想在单击删除按钮后删除它们。在此文件中是创建的数据:
@Component({
selector: 'condition-builder',
templateUrl: 'app/conditionbuilder.component.html',
providers: [ConditionService],
directives: [ConditionDetailComponent]
})
export class ConditionBuilderComponent implements OnInit {
conditions: Condition[] = [];
catalog: Condition[] = [];
constructor(private _conditionService: ConditionService) { }
getConditions() {
this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}
ngOnInit() {
this.getConditions();
}
onChange(conditionsIndex, catalogIndex) {
//console.log(selectedCondition);
//console.log(conditionsIndex);
console.log(catalogIndex);
this.conditions[conditionsIndex] = this.catalog[catalogIndex];
}
newCondition() {
this.conditions.push(this.catalog[0]);
}
deleteCondition() {
this.conditions.pop();
}
}
我希望访问条件数据或方法deleteCondition();在这个文件中:
export class SelectCondition extends Condition {
public name: string = 'select';
public fileValue: string;
public selectedOperator: string = 'in';
public selectOperators: Condition[] = [
"in"
];
selectFile() {
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$('.btn-file :file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
console.log(input.val());
}
});
}
deleteCondition() {
console.log('check');
conditions.pop();
}
}
如何从当前条件访问数据并将其删除。这里有一些截图:
首先它是这样的:https://www.dropbox.com/s/92z2oe7f4w5x2b5/conditions.jpg?dl=0这里删除最后创建的。
但我想分别删除每个条件:https://www.dropbox.com/s/ptwq6sk6da4p21k/new.jpg?dl=0
答案 0 :(得分:2)
您需要在引导应用程序时指定服务提供者:
bootstrap(AppComponent, [ConditionService]);
这样,在注入时,您将在整个应用程序中共享相同的服务实例。
请小心从组件的任何providers
属性中删除该服务。
您还可以将服务注入SelectCondition
服务:
@Injectable()
export class SelectCondition extends Condition {
constructor(private service: ConditionService) {
}
deleteCondition() {
console.log('check');
service.conditions.pop();
}
}
在引导您的应用程序时,不要忘记也添加此服务:
bootstrap(AppComponent, [ConditionService, SelectCondition]);