У меня есть метод в component.ts
, который выполняет службу, например:
this._usuariosServices.listarPerfiles().subscribe(perfiles => {
this.perfilesList = perfiles;
this.perfiles = perfiles.map(item => {
return {
id: item.id,
text: item.nombre
};
});
});
Таким образом, я и устанавливаю выпадающий список SELECT2
Теперь в том же компоненте в ngOnInit()
Я предварительно загружаю данные представления редактирования, например:
if (this.id != 0) {
this._usuariosServices.obtener(this.id).subscribe((usr: any) => {
usuarioJson = usr.json();
this.model.email = usuarioJson.email;
this.model.nombre = usuarioJson.nombre;
this.model.apellido = usuarioJson.apellido;
usuarioJson.empresas.forEach(element => {
var id = element;
this.checked.push(id);
});
console.log(usuarioJson);
usuarioJson.perfiles.forEach(element => {
var id = usuarioJson.perfilId;
console.log(element);
});
});
} else {
this.model = {};
}
// there is where I load selected one
numbreChanged(e: any) {
this.model.perfil = e.value;
}
Таким образом, все поля загружаются с правильными данными, кроме поля select2, как вы можете видеть, что у меня есть:
numbreChanged(e: any) {
this.model.perfil = e.value;
}
Но он всегда загружает первый выбранный вариант.Что мне нужно сделать, это загрузить текущее значение идентификатора?конечно, когда это условие истинно if (this.id != 0){
Поэтому я пытаюсь сделать как другие поля, такие как: this.model.perfiles = usuarioJson.perfilid;
, но он все еще получает первый вариант.
component.html:
<select2 [data]="perfiles" [width]="'100%'" (valueChanged)="numbreChanged($event)"></select2>
Полныйкомпонент:
import { Component, Input, OnInit, ViewEncapsulation } from "@angular/core";
import { Router, ActivatedRoute, Params } from "@angular/router";
import { ModalDismissReasons, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
import { ScriptLoaderService } from "../../../../../../_services/script-loader.service";
import { UsuariosService } from "../../../../../../_services/usuarios.service";
import { ToastrService } from "ngx-toastr";
import { Usuario } from "../../../../../../_models/usuarios";
@Component({
selector: "usuarios-detalles",
templateUrl: "./usuarios.detalle.component.html",
encapsulation: ViewEncapsulation.None
})
export class UsuariosDetalleComponent implements OnInit {
id: number = 0;
model: any = {};
usuario: Usuario;
empresasList: any[];
perfilesList: any[];
checked: Array<number> = [];
loading = false;
perfiles = [];
constructor(
private _script: ScriptLoaderService,
private _activatedRoute: ActivatedRoute,
private _usuariosServices: UsuariosService,
private _router: Router,
private toastr: ToastrService
) {}
ngOnInit() {
this.usuario = new Usuario();
this._activatedRoute.params.subscribe((params: Params) => {
this.id = params["id"];
});
var usuarioJson = null;
if (this.id != 0) {
this._usuariosServices.obtener(this.id).subscribe((usr: any) => {
usuarioJson = usr.json();
this.model.email = usuarioJson.email;
this.model.nombre = usuarioJson.nombre;
this.model.apellido = usuarioJson.apellido;
this.model.perfiles = usuarioJson.perfilId
usuarioJson.empresas.forEach(element => {
var id = element;
this.checked.push(id);
});
console.log(usuarioJson);
usuarioJson.perfiles.forEach(element => {
var id = usuarioJson.perfilId;
console.log(element);
});
});
} else {
this.model = {};
}
this._usuariosServices.listarPerfiles().subscribe(perfiles => {
this.perfilesList = perfiles;
this.perfiles = perfiles.map(item => {
return {
id: item.id,
text: item.nombre
};
});
});
}
updateChecked(option, event) {
if (event.target.checked) {
this.checked.push(option.id);
} else {
this.checked.forEach((item, index) => {
if (item === option.id) this.checked.splice(index, 1);
});
}
}
numbreChanged(e: any) {
this.model.perfil = e.value;
}
guardar() {
this.loading = true;
this.usuario.nombre = this.model.nombre;
this.usuario.apellido = this.model.apellido;
this.usuario.email = this.model.email;
this.usuario.perfilid = this.model.perfil;
this.usuario.empresas = [12];
debugger;
this._usuariosServices.guardar(this.usuario, this.id).subscribe(
data => {
if (this.id != 0) {
this.toastr.success("El registro se ha modificado correcatmente");
} else {
this.toastr.success("El registro se ha creado correctamente");
}
this.model = {};
this.loading = false;
this._router.navigate(["categorias/usuarios"]);
},
error => {
this.toastr.warning(error._body);
this.loading = false;
}
);
this.loading = false;
}
}
Как мне этого добиться?Привет