ViewContainerRef的Angular 2错误

时间:2017-03-28 20:19:18

标签: angular

我在Angular 2项目中使用此包(https://github.com/shlomiassaf/angular2-modal)作为Modals。

它工作正常,但在我的编辑页面中有一个决心,它显示了这个错误:

Unhandled Promise rejection: No provider for ViewContainerRef! ; Zone: <root> ; Task: Promise.then ;

我的编辑页面:

import { ActivatedRoute, Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
import {Location} from '@angular/common';
import {NgForm, FormBuilder, FormControl, FormGroup, Validators, FormArray} from '@angular/forms';
import { Overlay } from 'angular2-modal';
import { Modal } from 'angular2-modal/plugins/bootstrap';

import {CnpjValidator} from '../../shared/validators/cnpjValidator';
import {PartValidator} from './validators/valParts';

import { EmpresasCrudService } from './services/empresas-crud.service';

import {Config} from '../../shared/config/config.service';

import { ArraySocios, Empresa, Socios} from './models/arraySocios';

@Component({
  selector: 'empresas-edit',
  templateUrl: './empresas-edit.component.html'
})

export class EmpresasEditComponent implements Resolve<any>{

    fieldsSocios: any[] = [];
    showSocios: any[] = [];

    errors: any[] = [];
    form1 : FormGroup;
    form2 : FormGroup;
    form3 : FormGroup;
    form4 : FormGroup;

    contCampos = 1;
    maxCampos = 2;
    formBuilder;
    estados;

    // loading da table
    _loading = false;

    id: number;

    // Item
    data: any[];

    data2;

    // Item
    socios: any[];

    // Item
    socios2: any[];

    // Item
    socioss;

    // onde buscar os registros API
    _endpoint_url_estados: string = this.configService.getBaseUrl()+'contato/estados';
    endpoint_url_patch: string = this.configService.getBaseUrl()+'empresas/';
    endpoint_url_Get: string = this.configService.getBaseUrl()+'empresas/';

    public mask = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/];
    public maskCep = [/\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/];
    public maskTel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
    public maskCel = ['(', /\d/, /\d/, ')', /\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

    constructor(
        private _location: Location,
        formBuilder: FormBuilder,
        private dataService: EmpresasCrudService,
        private configService: Config,
        private router: Router,
        private route: ActivatedRoute,
        overlay: Overlay, 
        vcRef: ViewContainerRef, 
        public modal: Modal
    ){
        overlay.defaultViewContainer = vcRef;
        this.formBuilder = formBuilder;



    } // constructor
    resolve(route: ActivatedRouteSnapshot): Promise<any>|boolean {

        return new Promise((resolve, reject) => {

            if (route.params['id'] !== undefined) {
                this.dataService.getHttpEmpresaShow(this.endpoint_url_Get + route.params['id'])
                    .subscribe(result => {

                        if (result) {
                            console.log("ok");
                            return resolve(result);
                        } else {
                            console.log("erro");
                        }

                    });
            }
        });
    }

         alerts(titulo,alerta,botao) {
        this.modal.alert()
        .size('sm')
        .showClose(false)
        .isBlocking(true)
        .title(titulo)
        .body(`
           ${alerta}`)
        .okBtnClass(botao)
        .open()
        .catch((err: any) => console.log('ERROR: ' + err))
        .then((dialog: any) => { return dialog.result })
        .then((result: any) => { this.backClicked() })
        .catch(err => {}) // if were here it was cancelled (click or non block click);
  }

    disableBanco(e, b) {
        let valor = false;

        if(e !== null)
        {
            if(e.target.checked){
            valor = true;
            }
        }
        if(b){
            valor = true;
        }

        if(valor){
            this.form3.get('pessoa').enable();
            this.form3.get('banco').enable();
            this.form3.get('ag').enable();
            this.form3.get('conta').enable();
            this.form3.get('op').enable();
            this.form3.get('tipo_conta').enable();
            this.form3.get('favorecido').enable();
            this.form3.get('doc').enable();
            this.form3.get('obs').enable();

        }else{
            this.form3.get('pessoa').disable();
            this.form3.get('banco').disable();
            this.form3.get('ag').disable();
            this.form3.get('conta').disable();
            this.form3.get('op').disable();
            this.form3.get('tipo_conta').disable();
            this.form3.get('favorecido').disable();
            this.form3.get('doc').disable();
            this.form3.get('obs').disable();
        }

    }

    disableSocio(e, b) {
            let valor = false;

            if(e !== null)
            {
                if(e.target.checked){
                valor = true;
                }
            }
            if(b){
                valor = true;
            }

        if(valor){
            this.form4.controls['socios'].enable();


        }else{
            this.form4.controls['socios'].disable();
        }


    }


    submitForm(): void{


         /* this.form4.controls['socios']['controls'].forEach( key => {
                        teste.push(key.value);
                    });  */




    //Zera os erros
    this.errors = [];
    let form3Updated;
    let form4Updated;

    //Get Valores e Tira os pontos do CNPJ e CEP    
    let form1Updated = this.form1.value;
        form1Updated.cnpj ? form1Updated.cnpj = form1Updated.cnpj.replace(/\D/g, '') : "";
    let form2Updated = this.form2.value;
        form2Updated.cep ? form2Updated.cep = form2Updated.cep.replace(/\D/g, '') : "";

    //Se estiver checked o CadBanco ele atribui os dados
    if(this.form3.get('cadBanco').value == true){
        //Get valores form3
        form3Updated = this.form3.value;
    }

    var socios;

    //Se estiver checked o CadSocios ele atribui os dados
    if(this.form4.get('cadSocios').value == true){

        //Get valores form4
        form4Updated = this.form4.controls['cadSocios'].value;

        let result2 = [];

        let result = {
        "cadSocios" : true
        };

        for (let i = 0; i < this.form4.controls['socios']['controls'].length; i++) {
        this.form4.controls['socios']['controls'][i]['controls']['socio_id'].patchValue(this.socios[i] ? this.socios[i]['socio_id'] : 0);
        }

       this.form4.controls['socios']['controls'].forEach( key => {
                    result2.push(key.value);
                    }); 

        socios = Object.assign({}, result, {socios : result2});


    }

    //Monta os dados a serem cadastrados
    let data = Object.assign({}, form1Updated, form2Updated, form3Updated, socios);

       //Faz o PUT  
     let consulta = this.dataService.patchHttpEmpresas(this.endpoint_url_patch + this.id, data);
        consulta.subscribe(data => {
            this.alerts("Sucesso!", "Empresa editada com sucesso!", "btn btn-primary")
            }, 
            error => {
                console.log(error);
                window.scrollTo(0,0);
                if(error[0] == 422){                
                let fer = error[1];
                Object.keys(fer).forEach( key => {
                     this.errors.push(fer[key]); //value    
                });
                }else{
                 this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            });     


    }
    //Botão voltar
    backClicked() {
        this._location.back();
    }
    //Botão redirect to index
    redirectToIndex() {
        this.router.navigate(['/empresas']);
    }

    redirectToEmpresa() {
        this.router.navigate(['/empresas/' + this.id]);
    }

    //Adiciona campos socios
    adcSocios() {
    if(this.form4.get('cadSocios').value == true){


             // add address to the list
    const control = <FormArray>this.form4.controls['socios'];
    control.push(this.initAddress());
    }
    }

    //Adiciona campos socios
    removeSocios(i: number) {
    if(this.form4.get('cadSocios').value == true){
        // remove address from the list
    const control = <FormArray>this.form4.controls['socios'];
    control.removeAt(i);
    }
    }

    initAddress() {

        // initialize our address
        return this.formBuilder.group({
            nome: [{value: '', disabled: false}, [Validators.required]],
        participacao: [{value: '', disabled: false}, [Validators.required,
                Validators.pattern("[0-9]*")]],
                socio_id: ['']
        });

    }

    ngOnInit(){
        this.id = this.route.params['value']['id'];

        if(this.route.snapshot.data['data'])
        {
            this.data = this.route.snapshot.data['data']['data'];
            this.socios = this.route.snapshot.data['data']['socios']['socios'];
            this.socios2 = this.route.snapshot.data['data']['socios']['cadSocios'];
        }

        this.data.forEach((data) => {
            this.data = data;
        });


         this.form1 = this.formBuilder.group({
            razao_social: ['', [
                Validators.required
            ]],
            nome_fantasia: [],
            cnpj: ['', [
                Validators.required,
                CnpjValidator.cnpjValidator
            ]],
            insc_estadual: ['', [
                Validators.pattern("[0-9]*")
            ]],
            insc_municipal: ['', [
                Validators.pattern("[0-9]*")
            ]]

        });
        this.form2 = this.formBuilder.group({
            endereco: ['', [
                Validators.required
            ]],
            numero: ['', [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            complemento: [],
            bairro: ['', [
                Validators.required
            ]],
            cidade: ['', [
                Validators.required
            ]],
            estado_id: ['', [
                Validators.required
            ]],
            cep: ['', [
                Validators.required,
                Validators.pattern("[0-9]{2}[\.]?[0-9]{3}[-]?[0-9]{3}")
            ]],
            tel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            tel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{4}[-][0-9]{4}")
            ]],
            cel1: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            cel2: ['', [
                Validators.pattern("[\(][0-9]{2}[\)][0-9]{5}[-][0-9]{4}")
            ]],
            email: ['', [
                Validators.pattern("[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")
            ]],
            nome_contato: []

        });


        this.form3 = this.formBuilder.group({
            cadBanco: [{value: true, disabled: false}],
            pessoa: [{value: '', disabled: true}, [
                Validators.required
            ]],
            banco: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            ag: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[a-zA-Z0-9]*")
            ]],
            op: [{value: '', disabled: true}, []],
            tipo_conta: [{value: '', disabled: true}, [
                Validators.required,
                Validators.pattern("[0-9]*")
            ]],
            favorecido: [{value: '', disabled: true}, [
                Validators.required
            ]],
            doc: [{value: '', disabled: true}, []],
            obs: [{value: '', disabled: true}, []]


        });

        this.form4 = this.formBuilder.group({
            cadSocios: [{value: true, disabled: false}],

            socios: this.formBuilder.array([
                this.initAddress(),
            ])

        }, {validator: PartValidator.valPart()});


        this.getEstados();

        for (var _i = 1; _i < this.socios.length; _i++) {
            this.adcSocios();
        }
         var socios22 = [];
         this.socios.forEach((data) => {
        socios22.push({nome: data.nome, participacao: data.participacao});  
        });

        this.form4.patchValue({
        socios: socios22
        });

        this.disableBanco(null, this.data['cadBanco']);
        this.disableSocio(null, this.socios2);

    }

    getEstados(){
        let consulta = this.dataService.getHttpEstados(this._endpoint_url_estados);
        consulta.subscribe(
            estados => {
                estados.estados ? this.estados = estados.estados : ""
            },
            error =>  { this.alerts("Ops, houve um erro!", "Erro ao criar empresa!", "btn btn-danger") },
            () => ''

        );

    }

    getEmpresa(_endpoint_url){
        this._loading = true;

        let consulta = this.dataService.getHttpEmpresaShow(_endpoint_url);
        consulta.subscribe(
            people => {

                people.data ? this.data = people.data : "",
                    people.socios ? this.socios = people.socios.socios : "",
                    this._loading = false
            },
            error => {
                this._loading = false
                window.scrollTo(0,0);
                if(error[0] == 400){
                    this.alerts("Ops, houve um erro!", "A empresa selecionada não existe!", "btn btn-danger");
                }else{
                    this.alerts("Ops, houve um erro!", "Erro interno, contate o técnico!", "btn btn-danger");
                }
            }

        );

    }

}

1 个答案:

答案 0 :(得分:0)

您似乎正在使用组件作为解析器

implements Resolve<any>

这不起作用,因为如果您将ViewContainerRef作为依赖项,DI无法实例化它。