3

introducir la descripción de la imagen aquí

import { Component, OnInit,Input,OnChanges} from '@angular/core';
import { NgForm } from '@angular/forms';
import {objClass} from '../ObjClass';
import * as convert from 'xml-js';







@Component({
  selector: 'app-wsdl',
  templateUrl: './wsdl.component.html',
  styleUrls: ['./wsdl.component.css']
})
export class WsdlComponent implements OnInit {

	  i:number =0;
    @Input() currentMessageName:string;
  	@Input() nameSpace:string;
    messageNames:string[]=['--'];
    jsonSchema:string='';

    variable:objClass;

    objPortFather:objClass['objPortFather']=
            {"_attributes":{
                    'name':'default'},
                    'wsdl:operation':
                    [{"_attributes":{
                    'name':'default'},
                    'wsdl:input':{"_attributes":{
                        'name':'default',
                        'message':'default'
                    }},
                    'wsdl:output':{"_attributes":{
                        'name':'default',
                        'message':'default'}
                    },
                    'wsdl:fault':{"_attributes":{
                        'name':'default',
                        'message':'default'
                    }
                  }

                }]
            };

    objPortType:objClass['objPortType']=
  			[{"_attributes":{
                    'name':'default'},
                    'wsdl:input':{"_attributes":{
                        'name':'default',
                        'message':'default'}
                  },
                    'wsdl:output':{"_attributes":{
                        'name':'default',
                        'message':'default'}
                    },
                    'wsdl:fault':{"_attributes":{
                        'name':'default',
                        'message':'default'
                    }
                  }

                }];


    objPart:objClass['objPart']=
  				      [{"_attributes":{
                    'element':'default',
                    'name':'default'
                  }
                }];

    objMessages: objClass['objMessages']=[{"_attributes":{
                'name':'excepcionMsg'},
                'wsdl:part':[{"_attributes":{
                    'element':"tns:Excepcion",
                    'name':"excepcion"},
                }],
            }];


         objBindingFather:objClass['objBindingFather']=
              {"_attributes":{
                'name':'default',
                'type':'default'},
                'soap:binding':{"_attributes":{
                    'style':'default',
                    'transport': 'default'
                  },
                },
                "wsdl:operation":  [{"_attributes":{
          "name": 'default'},
          "wsdl:input": {"_attributes":{
            "name":'default'
          },
            "soap:body":{"_attributes":{
              "parts":'default',
              "use":'default'
            }
           },
           "soap:header":{"_attributes":{
             "message":'default',
             'part':'default',
             'use':'default'
             }
           }
          },
          "wsdl:output": {"_attributes":{
            "name": 'default'
            },
             "soap:body":{"_attributes":{
              "parts":'default',
              "use":'default'
            }
           },
           "soap:header":{"_attributes":{
             "message":'default',
             'part':'default',
             'use':'default'
             }
           }
          },
          "wsdl:fault": {"_attributes":{
            "name": 'default'},
            "soap:fault": {"_attributes": {
              "name": 'default',
              "use":'default'
            },
          }
        }
      }]
    }


    objBinding:objClass['objBinding']=
       [{"_attributes":{
          "name": 'default'},
          "wsdl:input": {"_attributes":{
            "name":'default'
          },
            "soap:body":{"_attributes":{
              "parts":'default',
              "use":'default'
            }
           },
           "soap:header":{"_attributes":{
             "message":'default',
             'part':'default',
             'use':'default'
             }
           }
          },
          "wsdl:output": {"_attributes":{
            "name": 'default'
            },
             "soap:body":{"_attributes":{
              "parts":'default',
              "use":'default'
            }
           },
           "soap:header":{"_attributes":{
             "message":'default',
             'part':'default',
             'use':'default'
             }
           }
          },
          "wsdl:fault": {"_attributes":{
            "name": 'default'},
            "soap:fault": {"_attributes": {
              "name": 'default',
              "use":'default'
            },
          }
        }
      }]

    definitions:{};

    objImport:objClass['objImport']=[{	"_attributes":{
                    'namespace':'http://www.banorte.com/ws/esb/general/Headers',
                    'schemeLocation':"SOAP/HeaderRequest.xsd"
                  },
                }];




  constructor() { }

  ngOnInit() {
  	this.objImport.push( {"_attributes":{
  		'namespace':'http://www.banorte.com/ws/esb/general/Headers',
      'schemeLocation':"SOAP/HeaderRequest.xsd"
    },
  },
  {"_attributes":{
      'namespace':'http://www.banorte.com/ws/esb/general/Headers',
      'schemeLocation':"SOAP/HeaderRequest.xsd"
    },
  })
}








ngOnChanges() {
  console.log('currentMessageName:'+ this.currentMessageName );
	if(this.currentMessageName){


		this.messageNames.push(this.currentMessageName);
    this.buildMessage(this.currentMessageName);
		}
  }





	buildMessage(currentMessageName:string){


		this.objPart.push({"_attributes":{
                     'element':"tns:"+currentMessageName+"Request",
                     'name':"tns:"+currentMessageName+"Request"
                   }
                 },
                 {"_attributes":{
                   'element':"tns:"+currentMessageName+'Reponse',
                   'name':'reponse'

                 }
               },
                 {"_attributes":{
                   'element':'mf:HeaderReq',
                   'name':'requestHeader'

                 }
		          });



		this.objMessages.push({ "_attributes":{
      'name':currentMessageName+"Request" },
      'wsdl:part':this.objPart
  })

    this.cleanObjPart();
//-----------------------------------------------------------------------------------------------------------------------
     this.objPart.push({"_attributes":{
       'name':'response' ,
       'element':'tns:'+currentMessageName+'Response'
     },
     },

    {"_attributes":{
      'element':'mf:HeaderRes',
      'name':'responseHeader'
        }
    });

    this.objMessages.push({"_attributes":{
      'name':currentMessageName+'Response'},
      'wsdl:part':this.objPart

    })

    this.cleanObjPart();



		this.objPortType.push({"_attributes":{
                    'name':this.currentMessageName},
                    'wsdl:input':{"_attributes":{
                        'name':this.currentMessageName+'Res',
                        'message':'tns:'+this.currentMessageName+'Response'
                    }},
                    'wsdl:output':{"_attributes":{
                        'name':this.currentMessageName+'Req',
                        'message':'tns'+this.currentMessageName+'Req'}
                    },
                    'wsdl:fault':{"_attributes":{
                        'name':'excepcion',
                        'message':'tns:excepcionMsg'
                    }
                  }
                });

    this.objPortFather={"_attributes":{'name':this.nameSpace+'SOAP'},
      'wsdl:operation':this.objPortType
    }




		this.objBinding.push({"_attributes":{
      "name":this.nameSpace
    },
    "wsdl:input":{"_attributes":{
      "name":this.currentMessageName+"Req"
      },
       "soap:body":{"_attributes":{
              "parts":'request',
              "use":'literal'
            }
           },
           "soap:header":{"_attributes":{
             "message":'tns'+this.currentMessageName+'Request',
             'part':'requestHeader',
             'use':'literal'
             }
           }
    },
    'wsdl:output':{"_attributes":{
      'name':this.currentMessageName+'Res'
    },
     "soap:body":{"_attributes":{
              "parts":'response',
              "use":'literal'
            }
           },
           "soap:header":{"_attributes":{
             "message":'tns'+this.currentMessageName+'Response',
             'part':'responseHeader',
             'use':'literal'
             }
           }
  },
"wsdl:fault":{"_attributes":{
  "name":'excepcion'
  },
  "soap:fault":{"_attributes":{
    "name":'excepcion',
    "use":'literal'
    }
  },
}

  });

        this.objBindingFather=
                {"_attributes":{
                'name':"default",
                'type':"default"
              },
                'soap:binding':{'_attributes':{
                    'style':"default",
                    'transport': "default"
                  },
                },
                "wsdl:operation": this.objBinding


        }


		this.i++;



	}



	displayCompleteJson(){

		 this.definitions=
		   {
        'wsdl:definitions':{"_attributes":{
        'xmlns:wsdl':'http://schemas.xmlsoap.org/wsdl/',
        'name':this.nameSpace,
        'xmlns:mf':"http://www.banorte.com/ws/esb/general/Headers",
        'xmlns:soap':"http://schemas.xmlsoap.org/wsdl/soap/" ,
        'xmlns:tns':"http://www.banorte.com/ws/esb/"+this.nameSpace,
        'xmlns:tnsEx':"http://www.banorte.com/ws/esb/common/ExcepcionGeneral" ,
        'xmlns:xsd':"http://www.w3.org/2001/XMLSchema",
        'targetNamespace':"http://www.banorte.com/ws/esb/"+this.nameSpace,
      },
        "wsdl:documentation": {
        "wsdl:appinfo": {"_attributes":{
        "source": "WMQI_APPINFO"},
        "MRWSDLAppInfo": {"_attributes":{
          "imported": "true"},
          "binding": {"_attributes":{
            "hasEncoding": "false",
            "imported": "true",
            "name": this.nameSpace+"SOAP",
            "originalBindingStyle": "document"}
          }
        }
      }
    },
        'wsdl:types':{
            'xsd:schema':{"_attributes":{
                'targetNamespace':'http://www.banorte.com/ws/esb/'+this.nameSpace},
                'xsd:include':{"_attributes":{
                  'schemaLocation':this.nameSpace+"V1.0.xsd"
                  }
                },
                'xsd:import':this.objImport,
              },
            },
            'wsdl:message':this.objMessages,
            'wsdl:portType':this.objPortFather,
            'wsdl:binding':this.objBindingFather,
            'wsdl:service':{"_attributes":{
                'name':this.nameSpace},
                'wsdl:port':{"_attributes":{
                    'name':this.nameSpace+"SOAP",
                    'binding':'tns:'+this.nameSpace+'SOAP'
                  },
                    'soap:address':{"_attributes":{
                      'location':'http://www.banorte.com.ws.esb.'+this.nameSpace+'/V1.0/'}
                    }
                }
            }
        }



        };



      var options = {compact: true, ignoreComment: true, spaces: 4};
      var result = convert.js2xml(this.definitions, options);
      console.log(result);

      this.jsonSchema = result;


    }

tengo una funcion en js para imprimir un archivo .xml el problema es que me dicen no puedo utilizar el dom directamente por lo que desconosco la manera correcta en la que podria utilizar mi funcion js en angular.

function saveTextAsFile()
{

  var textToWrite = document.getElementById("inputTextToSave").value;
  var textFileAsBlob = new Blob([textToWrite], {type:'application/xml'});
  var fileNameToSaveAs = "myNewFile.xml";
  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "My Hidden Link";
  window.URL = window.URL || window.webkitURL;
  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  downloadLink.onclick = destroyClickedElement;
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);
  downloadLink.click();
}

function destroyClickedElement(event)
{
  document.body.removeChild(event.target);
}

y trato de utilizarlo de esta manera incluyendo el script en el index.html pero marca error en el boton

<div class="container">
        <button (click)="saveTextAsFile()" >Save Text to File</button>

        <div class="row" id="inputTextToSave">

     {{jsonSchema}}


    <hr>
</div>
</div>

3 respuestas 3

0

¿Tienes algún componente en específico donde estés trabajando? Porque lo otro que puedes hacer es agregar tu código de js en el fichero app.component.ts como:

saveTextAsFile()
{
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'application/xml'});
    var fileNameToSaveAs = "myNewFile.xml";
    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "My Hidden Link";
    window.URL = window.URL || window.webkitURL;
    downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
    downloadLink.onclick = destroyClickedElement;
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}
destroyClickedElement(event)
{
    document.body.removeChild(event.target);
}

De esta manera debería funcionar tu botón.

7
  • Hola si estoy trabajando en un componente llamado wsdl.componet.wsdl de donde extraigo {{jsonschema}} y posteriormente quiero sacar ese contenido en el archivo por medio del boton, la manera en que me lo muestras tengo error en cuanto a webkitURL el 20 jul. 2018 a las 13:45
  • De casualidad puedes montar ese componente para verlo completo? el 20 jul. 2018 a las 13:52
  • listo ya lo he montado el 20 jul. 2018 a las 14:10
  • Tres preguntas, ¿podrías enseñarme que dice el error exactamente? ¿el código del botón está en el componente wsdl.component.html? ¿la variable {{jsonSchema}} te da error cuando la llamas en el index.html? el 20 jul. 2018 a las 14:51
  • he puesto una imagen de mi errror ,el boton si lo tengo en wsdl.html.por cierto para lo que busco hacer que es descargar el contenido mostrado en un archivo .xml me encontrado con el siguiente servicio npmjs.com/package/angular-download el 20 jul. 2018 a las 15:07
0

Puede que este sea un problema XY.

El código que muestras no tiene el error real. Lo que está pasando es que estas tratando de usar xml-js que es un paquete de NodeJS para servidores, no para navegadores. El entorno de servidor de NodeJS tiene una funcion llamada require() que no está disponible en los navegadores. Y por eso lanza el ReferenceError.

Tienes que buscar otra solución para trabajar con xml en el cliente.

La mejor solución que yo he encontrado esta aquí. Son dos archivos js que podés descargar uno es para convertir de xml a js y el otro es reverso. Lo que podés hacer es sacar las funciones de los archivos y ponerlos en tu componente.


PD: La comunidad de StackOverflow es de ayuda. Te recomiendo que intentés leer los errores que te de la consola, aunque estén en inglés, pueden direccionarte rápidamente al problema real. Así también nos ayudas a ayudarte :)

2
  • gracias, y tratare de ser mas explicito en cuanto a lo que pregunto el 20 jul. 2018 a las 20:13
  • Si la respuesta te fue de ayuda, podés marcarla como aceptada ;)
    – Nery Ortez
    el 21 jul. 2018 a las 22:56
0

hola siguiendo el consejo de Jerson Jimenes y moví mi función al componente que quiero que realice dicha función ademas de realizar unos cambios lo cual quedaría de la siguiente forma para su funcionamiento.

saveTextAsFile()
  {


      var textToWrite = (<HTMLInputElement>document.getElementById("inputTextToSave")).value
      var textFileAsBlob = new Blob([textToWrite], {type:'application/xml'});
      var fileNameToSaveAs = "myNewFile.xml";
      var downloadLink = document.createElement("a");
      downloadLink.download = fileNameToSaveAs;
      downloadLink.innerHTML = "My Hidden Link";
      window.URL = window.URL || (<any>window).webkitURL;
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
      downloadLink.onclick = this.destroyClickedElement;
      downloadLink.style.display = "none";
      document.body.appendChild(downloadLink);
      downloadLink.click();
  }
  destroyClickedElement(event)
  {
      document.body.removeChild(event.target);
  }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.