以下是家庭组件代码
import { Component, OnInit, OnChanges, EventEmitter, Input, Output} from '@angular/core';
import { LowerCasePipe } from '@angular/common';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { FormControl, FormGroup, Validators, NgControl, ValidatorFn, AbstractControl } from '@angular/forms';
import { Ng2Highcharts, Ng2Highmaps, Ng2Highstocks } from 'ng2-highcharts';
import { DashboardService, TruncatePipe,dateFormatterPipe,yyyymmddFormatPipe } from '../shared/index';
import { shareDataService } from '../shared/dashboardservice/shareuserdata';
import { ActivatedRoute, Router,Params } from '@angular/router';
import { NgbModal, ModalDismissReasons, NgbDateStruct, NgbActiveModal, NgbModalRef,NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
interface udpateEditComment {
pmComment: string;
}
interface userinfo{
userInfo:{
userID:string
};
}
@Component({
moduleId: module.id,
selector: 'sd-home',
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
providers: [shareDataService]
})
export class HomeComponent implements OnInit {
greeting:string = "Enter PIN";
newName: string = '';
errorMessage: string;
dashboardData: any[] = [];
UserInfo: any[] = [];
GetReports: any[] = [];
CurrentReport: any[] = [];
getdashReportsdata: any[] = [];
currentUser: any[] = [];
high: number;
low: number;
medium: number;
pichart: any = {};
highAlerts: any[] = [];
mediumAlerts: any[] = [];
lowAlerts: any[] = [];
getChartData: any[] = [];
userinfo1 = {};
severity: any = "";
totalPageNumbers: any[] = [];
selectedReportId: number = 1;
getAdminMenus: any[] = [];
pageloader: boolean = true;
graphPageloader: boolean = false;
CatPageloader: boolean = false;
selectedReport: {} = { Title: '', Cat: '' };
totalCount: number = 0;
userrole: any = "1";
pageTitle: any = "Porfolio Dashboard";
closeResult: string;
editCommentsData: any[] = [];
selectedAlertReportID: string = '';
modalRef: NgbModalRef;
editCommentPageloader:boolean=true;
riskheaderData={};
udpateEditComment: FormGroup;
userid:any;
roleID:any;
queryData: {} = {
repid: "1",
roleid: "1",
reportCat: "PIM",
totalAlerts: "0"
}
/**
* highcharts
*
*/
piechartrender(high, low, mediume, contClass) {
this.pichart = {
chart: {
renderTo: 'container',
className: contClass,
backgroundColor: 'transparent',
plotBorderWidth: null,
plotShadow: false,
type: 'pie',
margin: [0, 0, 0, 0],
spacingTop: 0,
spacingBottom: 0,
spacingLeft: 0,
spacingRight: 0
},
credits: {
enabled: false
},
legend: {
align: "right",
itemDistance: 20,
layout: "vertical",
y: -50,
x: -50,
symbolHeight: 12,
symbolWidth: 12,
itemStyle: {
fontWeight: 'normal'
},
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
borderWidth: 0,
minSize: 10,
radialGradient: null,
showInLegend: true,
size: '95%',
dataLabels: {
distance: -20,
format: '{point.y}',
style: {
textShadow: false, color: 'white'
}
}
}
},
series: [{
name: 'Alerts',
data: [{
name: 'High',
y: high,
color: "#eb3228",
}, {
name: 'Low',
y: low,
color: "#7b7a79",
}, {
name: 'Medium',
y: mediume,
color: "#ec8123",
}]
}]
}
}
constructor(private route: Router, private aRoute: ActivatedRoute,public DashboardService: DashboardService, public config: shareDataService, private aroute: ActivatedRoute, private modalService: NgbModal,private formatDate:NgbDateParserFormatter) { }
onRoleChange(roleid: boolean) {
this.queryData["roleid"] = roleid;
this.getData(roleid);
this.userrole = roleid;
this.riskheaderData.roleid=roleid;
sessionStorage.setItem("riskHeaderData",JSON.stringify(this.riskheaderData));
}
ngOnInit() {
this.getUserinfo();
}
getUserinfo() {
let userinfo="userInfo={'userID':'"+ this.config.user_id +"'}";
this.DashboardService.rmdService(this.config.homePageData,userinfo).subscribe(
userrole => {
this.userrole = userrole.UserRoles[0].roleid;
this.queryData["roleid"] = this.userrole;
this.riskheaderData.roleid=this.userrole;
sessionStorage.setItem("riskHeaderData",JSON.stringify(this.riskheaderData));
this.getData(this.userrole);
}
)
}
getData(roleid) {
let userinfo="userInfo={'userID':'"+ this.config.user_id +"','roleID':'"+ roleid +"'}";
this.DashboardService.rmdService(this.config.homePageData,userinfo)
.subscribe(
userData => {
this.dashboardData = userData;
this.userinfo1 = this.dashboardData;
//this.shareDataService.setUserinfo(this.dashboardData);
if (this.dashboardData && this.dashboardData.PIM) {
this.CurrentReport = this.dashboardData.PIM;
this.getReportsdata(roleid, this.dashboardData.PIM[0].rptID, 1);
// this.CurrentReport.push({'reportCat':'PIM'});
this.selectedAlertReportID = this.dashboardData.PIM[0].rptID;
this.selectedReport["Title"] = this.dashboardData.PIM[0].rptName;
this.selectedReport["Cat"] = "PIM";
}
else if (this.dashboardData && this.dashboardData.PC) {
// this.CurrentReport.push({'reportCat':'PC'});
this.CurrentReport = this.dashboardData.PC;
this.getReportsdata(roleid, this.dashboardData.PC[0].rptID, 1);
this.selectedAlertReportID = this.dashboardData.PC[0].rptID;
this.selectedReport["Title"] = this.dashboardData.PC[0].rptName;
this.selectedReport["Cat"] = "PC";
}
else if (this.dashboardData && this.dashboardData.ET) {
// this.CurrentReport.push({'reportCat':'ET'});
this.CurrentReport = this.dashboardData.ET;
this.getReportsdata(roleid, this.dashboardData.ET[0].rptID, 1);
this.selectedAlertReportID = this.dashboardData.ET[0].rptID;
this.selectedReport["Title"] = this.dashboardData.ET[0].rptName;
this.selectedReport["Cat"] = "ET";
}
else if (this.dashboardData && this.dashboardData.APP_ADV) {
// this.CurrentReport.push({'reportCat':'APP_ADV'});
this.CurrentReport = this.dashboardData.APP_ADV;
this.getReportsdata(roleid, this.dashboardData.APP_ADV[0].rptID, 1);
this.selectedAlertReportID = this.dashboardData.APP_ADV[0].rptID;
this.selectedReport["Title"] = this.dashboardData.APP_ADV[0].rptName;
this.selectedReport["Cat"] = "APP_ADV";
}
if (this.dashboardData.CutomizedMenu.length != 0 || !this.dashboardData.CutomizedMenu) {
this.dashboardData.adminTitle = this.dashboardData.CutomizedMenu[0].itemname;
this.getAdminMenus = [];
for (var key in this.dashboardData.CutomizedMenu) {
if (this.dashboardData.CutomizedMenu.hasOwnProperty(key)) {
let element = this.dashboardData.CutomizedMenu[key];
if (element["itemlevel"] == 2) {
if(element['itemid'] == 3 || element['itemname']== "Manage Users"){
element["page_link"]="manageuser";
}
if(element['itemid'] == 5 || element['itemname']== "Manage Risk Severity Divergence Rates"){
element["page_link"]="severity";
}
this.getAdminMenus.push(element);
}
}
}
}
},
error => this.errorMessage = <any>error
);
}
fliterpage(repid, reportCat, reportName) {
this.queryData["repid"] = repid;
this.queryData["reportCat"] = reportCat;
this.queryData["reportName"] = reportName;
sessionStorage.setItem('userData', JSON.stringify(this.queryData));
this.route.navigate(['/filter', encodeURI(JSON.stringify(this.queryData))]);
}
getReportsdata(roleid, repid, pageNumber:string="1") {
let reportData="request={'userID':'"+ this.config.user_id +"','rptID':'"+repid+"','TplName':'PIMChart','pageNumber':'"+pageNumber+"','roleID':'"+roleid+"','filtervals':{'IACode':'','branch':'','portfolio':'','account':'','alerttype':'','severity':'','agegroup':''}}";
this.DashboardService.rmdService(this.config.pieChartData,reportData).subscribe(
data => {
this.pageloader = false;
this.graphPageloader = false;
this.CatPageloader = false;
this.getdashReportsdata = data;
this.userinfo1.graphData = this.getdashReportsdata;
if (this.getdashReportsdata && this.getdashReportsdata.SeverityDS) {
this.severity = this.keysToLowerCase(this.getdashReportsdata.SeverityDS);
let contClass = " ";
if (this.severity.high[0].totalAlerts != 0) {
this.highAlerts = this.severity.high[0].totalAlerts;
} else {
this.highAlerts = null;
contClass += " high ";
}
if (this.severity.low[0].totalAlerts != 0) {
this.lowAlerts = this.severity.low[0].totalAlerts;
} else {
this.lowAlerts = null;
contClass += " low ";
}
if (this.severity.medium[0].totalAlerts != 0) {
this.mediumAlerts = this.severity.medium[0].totalAlerts;
} else {
this.mediumAlerts = null;
contClass += " medium ";
}
this.totalCount = this.severity.medium[0].totalAlerts + this.severity.low[0].totalAlerts + this.severity.high[0].totalAlerts;
this.queryData["totalAlerts"] = this.totalCount;
this.riskheaderData.totalAlerts=this.totalCount;
sessionStorage.setItem("riskHeaderData",JSON.stringify(this.riskheaderData));
this.piechartrender(this.highAlerts, this.mediumAlerts, this.lowAlerts, contClass);
}
this.getChartData = [];
for (var key in this.getdashReportsdata.GraphData.Graph_Data) {
if (this.getdashReportsdata.GraphData.Graph_Data.hasOwnProperty(key)) {
let element = this.getdashReportsdata.GraphData.Graph_Data[key];
// element["Risk"] = new TruncatePipe().transform(element["Risk"], 10000, "...");
element["Risk_truncate"] = new TruncatePipe().transform(element["Risk"],['35','...']);
element["Severity"] = new LowerCasePipe().transform(element["Severity"]);
// element["alert_id"] = element["Alert ID"];
this.getChartData.push(element);
}
}
//pagination
let currentPage = this.getdashReportsdata.PageNumber;
let numberPerPage = 10;
let totalPage = 0;
let totalPageShow = 5;
this.getdashReportsdata["previous"] = false;
this.getdashReportsdata["next"] = false;
// totalPage=Math.ceil(this.getdashReportsdata.TotalPageCount/numberPerPage);
totalPage = this.getdashReportsdata.TotalPageCount;
if (currentPage > 1) {
this.getdashReportsdata["previous"] = true;
}
if (currentPage != totalPage) {
this.getdashReportsdata["next"] = true;
}
if (totalPage >= totalPageShow && currentPage >= totalPageShow) {
this.totalPageNumbers = [1, "...", currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2, "...", totalPage];
}
if (totalPage == currentPage) {
this.totalPageNumbers = [1, "...", currentPage - 4, currentPage - 3, currentPage - 2, currentPage - 1, currentPage];
}
if (currentPage == totalPage - 1 || currentPage == totalPage - 2) {
this.totalPageNumbers = [1, "...", totalPage - 4, totalPage - 3, totalPage - 2, totalPage - 1, totalPage];
}
if (totalPage < 5) {
this.totalPageNumbers = Array(totalPage).fill().map((x, i) => i+1);
}
if (totalPage > 5 && currentPage < 5) {
this.totalPageNumbers = [1, 2, 3, 4, 5, "...", totalPage];
}
},
error => this.errorMessage = <any>error
);
}
onCategoryChange(reportCat) {
switch (reportCat) {
case "1":
this.selectedReportId = this.dashboardData.PIM[0].rptID;
this.selectedReport["Title"] = this.dashboardData.PIM[0].rptName;
this.selectedReport["Cat"] = "PIM";
this.getReportsdata(this.userrole, this.selectedReportId, 1);
this.CatPageloader = true;
if (this.dashboardData) {
this.CurrentReport = this.dashboardData.PIM;
this.CurrentReport['reportCat'] = "PIM";
this.CurrentReport.push({ 'reportCat': 'PIM' });
}
break;
case "2":
this.selectedReportId = this.dashboardData.PC[0].rptID;
this.selectedReport["Title"] = this.dashboardData.PC[0].rptName;
this.selectedReport["Cat"] = "PC";
this.getReportsdata(this.userrole, this.selectedReportId, 1);
this.CatPageloader = true;
if (this.dashboardData) {
this.CurrentReport = this.dashboardData.PC;
}
break;
case "3":
this.selectedReportId = this.dashboardData.ET[0].rptID;
this.selectedReport["Title"] = this.dashboardData.ET[0].rptName;
this.selectedReport["Cat"] = "ET";
this.getReportsdata(this.userrole, this.selectedReportId, 1);
this.CatPageloader = true;
if (this.dashboardData) {
this.CurrentReport = this.dashboardData.ET;
}
break;
case "4":
this.selectedReportId = this.dashboardData.APP_ADV[0].rptID;
this.selectedReport["Title"] = this.dashboardData.APP_ADV[0].rptName;
this.selectedReport["Cat"] = "APP_ADV";
this.getReportsdata(this.userrole, this.selectedReportId, 1);
this.CatPageloader = true;
if (this.dashboardData) {
this.CurrentReport = this.dashboardData.APP_ADV;
}
break;
default:
this.CurrentReport = this.dashboardData.PIM;
this.selectedReport["Title"] = this.dashboardData.PIM[0].rptName;
this.selectedReport["Cat"] = "PIM";
}
}
keysToLowerCase(obj: string | Object | number | boolean) {
/*if (!typeof (obj) === "object" || typeof (obj) === "string" || typeof (obj) === "number" || typeof (obj) === "boolean") {
return obj;
}*/
var keys = Object.keys(obj);
var n = keys.length;
var lowKey;
while (n--) {
var key = keys[n];
if (key === (lowKey = key.toLowerCase()))
continue;
obj[lowKey] = this.keysToLowerCase(obj[key]);
delete obj[key];
}
return (obj);
}
selectedPage(attr) {
if (attr != '...') {
this.graphPageloader = true;
this.getReportsdata(this.userrole, this.selectedReportId, attr);
}
}
getEditComments(alertid) {
this.editCommentPageloader=true;
this.udpateEditComment = new FormGroup({
ddPmCom: new FormControl(),
ddTimeRes: new FormControl(),
additionalPMComment: new FormControl(),
pm_UpdateExistingComment: new FormControl(),
lastPMCommentUpdatedBy: new FormControl(),
lastPMCommentDate: new FormControl(),
headoff_com: new FormControl(),
resolutionDate: new FormControl(),
additionalHeadOfficeComment: new FormControl(),
hdOff_UpdateExistingComment: new FormControl(),
lastCommentUpdateBy: new FormControl(),
lastCommentUpdateDate: new FormControl(),
alertId: new FormControl(alertid),
});
let editcomment="editvals={'rptID':'"+ this.selectedAlertReportID +"','altID':'"+ alertid +"','roleID':'"+ this.queryData["roleid"] +"'}";
this.DashboardService.rmdService(this.config.editComments,editcomment)
.subscribe(
editCommentData => {
this.editCommentsData = editCommentData;
this.editCommentPageloader=false;
let resDate=new dateFormatterPipe().transform(this.editCommentsData.resolutionDate.Text);
let pmcommentdate=new yyyymmddFormatPipe().transform(this.editCommentsData.lastPMCommentDate.Text);
let commentupdatedate=new yyyymmddFormatPipe().transform(this.editCommentsData.lastCommentUpdateDate.Text);
let formatedate=this.formatDate.format()
this.udpateEditComment = new FormGroup({
//pm Comments
ddPmCom: new FormControl({value:this.editCommentsData.Comments["0"].disp_com,disabled:this.editCommentsData.pMComment.Enabled===false}),
// txPmComText:new FormControl(this.editCommentsData.txPmComText),
ddTimeRes: new FormControl({value:this.editCommentsData.Comments["0"].time_to_res,disabled:this.editCommentsData.timeToResolution.Enabled===false}),
additionalPMComment: new FormControl(this.editCommentsData.additionalPMComment.Text),
pm_UpdateExistingComment: new FormControl(),
lastPMCommentUpdatedBy: new FormControl(this.editCommentsData.lastPMCommentUpdatedBy.Text),
lastPMCommentDate: new FormControl(pmcommentdate),
//headoffice Comments
headoff_com: new FormControl({value:this.editCommentsData.Comments["0"].headoff_com,disabled:this.editCommentsData.headOfficeComment.Enabled===false}),
resolutionDate: new FormControl(resDate),
additionalHeadOfficeComment: new FormControl(this.editCommentsData.additionalHeadOfficeComment.Text),
hdOff_UpdateExistingComment: new FormControl(),
lastCommentUpdateBy: new FormControl(this.editCommentsData.lastCommentUpdateBy.Text),
lastCommentUpdateDate: new FormControl(commentupdatedate),
alertId: new FormControl(alertid),
});
},
error => this.errorMessage = <any>error
);
}
onSaveComment({ value, valid }: { value: udpateEditComment, valid: boolean }) {
let resDate= value.resolutionDate;
resDate=resDate.day+"-"+resDate.month+"-"+resDate.year;
let savevalue="savevals={'rptID':'"+ this.selectedAlertReportID +"','roleID':'"+ this.queryData["roleid"] +"','userId':'"+ this.config.user_id +"','altID':'"+ value.alertId+"','PMComment':'"+value.ddPmCom+"','TimetoResolution':'"+ value.ddTimeRes+"','AdditionalPMComment':'"+value.additionalPMComment+"','Updateexistingcomment':'"+value.pm_UpdateExistingComment+"','HeadOfficeComment':'"+ value.headoff_com +"','AdditionalHeadOfficeComment':'"+value.additionalHeadOfficeComment+"','UpdateHeadexistingComment':'"+value.hdOff_UpdateExistingComment+"','ResolutionDate':'"+resDate+"'}";
this.DashboardService.rmdService(this.config.SaveComment,savevalue)
.subscribe(
saveComment => {
alert(saveComment);
this.modalRef.close(saveComment)
},
error => this.errorMessage = <any>error
);
}
// open(content,alertid) {
// this.getEditComments(alertid);
// this.modalRef= this.modalService.open(content).result.then((result) => {
// this.closeResult = `Closed with: ${result}`;
// }, (reason) => {
// this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
// });
// }
open(content, alertid) {
this.getEditComments(alertid);
this.modalRef = this.modalService.open(content);
this.modalRef.result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
openWhatsNew(whatsNew) {
this.modalService.open(whatsNew).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.whatsNewReason(reason)}`;
});
}
private whatsNewReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
model: NgbDateStruct;
isWeekend(date: NgbDateStruct) {
const d = new Date(date.year, date.month - 1, date.day);
return d.getDay() === 0 || d.getDay() === 6;
}
isDisabled(date: NgbDateStruct, current: { month: number }) {
return date.month !== current.month;
}
}
模板不会使用模拟数据呈现,在茉莉花规格中向Angular2应用程序显示“未定义不是函数”
以下是规范文件
import { async, inject, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { NameListService, DashboardService, TruncatePipe } from '../shared/index';
import { shareDataService } from '../shared/dashboardservice/shareuserdata';
import { HomeComponent } from './home.component';
import { FormControl, FormGroup, Validators, NgControl, ValidatorFn, AbstractControl,FormsModule,ReactiveFormsModule } from '@angular/forms';
import { Ng2Highcharts, Ng2Highmaps, Ng2Highstocks } from 'ng2-highcharts';
import { Header } from '../shared/header/index';
import { ActivatedRoute, Router, Params,RouterModule } from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
describe('Home Component Test Case', () => {
let fixture:any;
let homeComponent:any;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent,Header,Ng2Highcharts],
imports:[RouterModule,FormsModule,ReactiveFormsModule,NgbModule.forRoot()],
providers:[]
});
TestBed.overrideComponent(HomeComponent, {
set: {
providers: [{ provide: DashboardService, useClass: MockDashboardService },
{provide: Router, useClass: MockRouter},
{provide: shareDataService, useClass: MockSharedDataService},
{provide: ActivatedRoute, useClass: MockActivatedRoute}
]
},
}).compileComponents().then( () => {
fixture = TestBed.createComponent(HomeComponent);
homeComponent = fixture.componentInstance;
homeComponent.dashboardData = {
"UserInfo": [
{
"empCode": 3049,
"loginID": "311243935",
"userLastName": "Rao",
"userFirstName": "Ramesh",
"active": true,
"language": "E",
"userName": "Ramesh Rao"
}
],
"UserRoles": [
{
"roleid": 1,
"ROLENAME": "Investment Advisor",
"IAcode": "B49,DLA,FXF,KPN,LZ2,M72,NNL,NNS,P5J,P7Q,P7T,PHL,TL7",
"branchCode": "301,311,421,423,439,544,631,647,736,771,806",
"REF_ID": "PIM"
}
]
};
homeComponent.pageloader = false;
homeComponent.getData= function(roleid){
};
console.log(homeComponent);
console.log("------------------------------");
console.log(fixture.nativeElement);
});
}));
it('Home component instance should be defined and template should be rendered', async(() => {
expect(homeComponent).toBeDefined();
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('#dashboard_data').length).toBe(1);
}));
});
执行“fixture.detectChanges()”时,它会抛出以下错误:
> Failed: undefined is not a function
> TypeError: undefined is not a function
> at HomeComponent.getUserinfo (C:/Users/323126953/Desktop/prjt/dist/dev/app/home/home.component.js:9:7509)
> at HomeComponent.ngOnInit (C:/Users/323126953/Desktop/prjt/dist/dev/app/home/home.component.js:9:7150)
> at DebugAppView._View_HomeComponent_Host0.detectChangesInternal
> (HomeComponent_Host.ngfactory.js:44:82)
> at DebugAppView.AppView.detectChanges (C:/Users/323126953/Desktop/prjt/node_modules/@angular/core/bundles/core.umd.js:9
> 566:18)
> at DebugAppView.detectChanges (C:/Users/323126953/Desktop/prjt/node_modules/@angular/core/bundles/core.umd.js:9671:48)
> at ViewRef_.detectChanges (C:/Users/323126953/Desktop/prjt/node_modules/@angular/core/bundles/core.umd.js:7668:24)
> at ComponentFixture._tick (C:/Users/323126953/Desktop/prjt/node_modules/@angular/core/bundles/core-testing.umd.js:277:3
> 6)
感谢任何帮助。