如何将此 javascript 和 HTML 代码添加到 Angular 项目中?我可以从 javascript 函数中以角度呈现 html 吗?
Posted
技术标签:
【中文标题】如何将此 javascript 和 HTML 代码添加到 Angular 项目中?我可以从 javascript 函数中以角度呈现 html 吗?【英文标题】:How Do I add this javascript and HTML code into an angular project? and can i render html from javascript function in angular? 【发布时间】:2020-02-27 21:58:04 【问题描述】:如何将此 javascript 和 HTML 代码添加到 Angular 项目中? 我已将 func.js 放在我的 Angular 项目和 app.component.ts 文件中的 src 文件夹中 我尝试导入并使用 ngAfterViewInit() 来加载和使用 javascript 函数
这些是我尝试添加到 Angular Web 应用程序的 javascript 和 html 文件:
funcs.js
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource =
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, , quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = 'prepopulate': true ;
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getData(res, param, log)
var data = null;
var url = endpoint + '/' + res + param;
$.ajax(
accepts:
json: 'application/fhir+json',
xml: 'application/fhir+xml'
,
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response)
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
,
beforeSend: function (xhr)
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
,
error: function (err)
if (log)
console.error('getData: FAILED - "' + url + '"')
);
return data;
//recursively inject valueset into lhc json
function injectValueSet(lhcJson)
if (lhcJson && 'items' in lhcJson)
lhcJson.items.forEach(e =>
injectValueSet(e);
);
else
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet)
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
//save form
function save()
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
//open file
function openQues()
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event =>
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
;
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
// get valueSet count
function getValueSetCount()
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response)
count = response.total;
return count;
//get all valueSets id
function getValueSetIds()
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response)
if ('entry' in response && response.entry.length > 0)
response.entry.forEach(e =>
if ('resource' in e && 'id' in e.resource && 'url' in e.resource)
ids.push(
'id': e.resource.id,
'url': e.resource.url
);
);
return ids;
//create valueSet array for form fields
function createValueSetData()
var data = , dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids)
failedIds = [];
ids.forEach(idSet =>
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0)
dataValueSet = [];
response.expansion.contains.forEach(e =>
dataValueSet.push(
'text': e.code + ' - ' + e.display,
'code': e.code
);
);
data[idSet.url] = dataValueSet;
else
failedIds.push(idSet.id);
);
if (failedIds.length > 0)
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
return data;
//save json to file
function saveJsonToFile(json, fileName)
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], type: 'text/plain' );
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
**Html file :**
<!DOCTYPE html>
<html>
<head>
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
</head>
<body>
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
【问题讨论】:
How do I include a JavaScript script file in Angular and call a function from that script?的可能重复 我遵循了这些步骤,特别是来自***.com/questions/49526681/…,但它对我不起作用 【参考方案1】:import Component, OnInit from '@angular/core';
import * as $ from 'jquery';
import OpenQues,save from '../assets/scripts.js'
declare var tesing: any;
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
)
export class AppComponent implements OnInit
title = 'Look jQuery Animation working in action!';
public ngOnInit()
$.getScript('./assets/scripts.js');
public open()
OpenQues();
public save()
save();
这对我有用
【讨论】:
谢谢 - 它可以工作,但需要在 npm install --save jquery npm install --save @types/jquery 之前安装以下包【参考方案2】:首先通过angular cli创建一个新组件,并在.ts文件中添加变量声明,即
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource =
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, , quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = 'prepopulate': true ;
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
然后在.html页面中添加html代码
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
然后在html文件的tag里面添加函数
function getData(res, param, log)
var data = null;
var url = endpoint + '/' + res + param;
$.ajax(
accepts:
json: 'application/fhir+json',
xml: 'application/fhir+xml'
,
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response)
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
,
beforeSend: function (xhr)
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
,
error: function (err)
if (log)
console.error('getData: FAILED - "' + url + '"')
);
return data;
//recursively inject valueset into lhc json
function injectValueSet(lhcJson)
if (lhcJson && 'items' in lhcJson)
lhcJson.items.forEach(e =>
injectValueSet(e);
);
else
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet)
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
//save form
function save()
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
//open file
function openQues()
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event =>
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
;
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
// get valueSet count
function getValueSetCount()
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response)
count = response.total;
return count;
//get all valueSets id
function getValueSetIds()
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response)
if ('entry' in response && response.entry.length > 0)
response.entry.forEach(e =>
if ('resource' in e && 'id' in e.resource && 'url' in e.resource)
ids.push(
'id': e.resource.id,
'url': e.resource.url
);
);
return ids;
//create valueSet array for form fields
function createValueSetData()
var data = , dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids)
failedIds = [];
ids.forEach(idSet =>
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0)
dataValueSet = [];
response.expansion.contains.forEach(e =>
dataValueSet.push(
'text': e.code + ' - ' + e.display,
'code': e.code
);
);
data[idSet.url] = dataValueSet;
else
failedIds.push(idSet.id);
);
if (failedIds.length > 0)
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
return data;
//save json to file
function saveJsonToFile(json, fileName)
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], type: 'text/plain' );
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
重要的是,将所有脚本导入添加到 app 文件夹之外的主索引 index.html 中
在头部添加这个 -
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
还有这个-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
最后但同样重要的是,在 app.component.html 文件中添加已创建组件的选择器
在 .html 文件的创建组件中应该看起来像这样,将其添加到 app.component.html
【讨论】:
以上是关于如何将此 javascript 和 HTML 代码添加到 Angular 项目中?我可以从 javascript 函数中以角度呈现 html 吗?的主要内容,如果未能解决你的问题,请参考以下文章
如何将此 Javascript 滑块转换为 OOP 解决方案?