- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
更新 1 开始
问题是,一旦我再次绘制 FormArray,我就无法按顺序获取所有城市和位置,这只是因为循环。无论如何,我是 TS 的新手,您可能会理解得更好。再次感谢。
import { Component, OnInit, NgZone } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { SharedService } from '../../../layouts/shared-service';
import { MdSnackBar, MdSnackBarConfig, MdDialog, MdDialogRef, MdDialogConfig } from '@angular/material';
// Added employee services
import { VehiclePlanService } from '../../../service/vehicle-plan.service';
import { PlanService } from '../../../service/plan.service';
import { LocationService } from '../../../service/location.service';
import { VehicleMakeService } from '../../../service/vehicle-make.service';
import { CommonService } from '../../../service/common.service'; // call the common services
import { PlanInterface } from './plans.interface';
import 'rxjs/add/operator/toPromise';
declare var $: any;
@Component({
selector: 'app-vehicle-plan',
templateUrl: './vehicle-plan.component.html',
styleUrls: ['./vehicle-plan.component.scss']
})
export class VehiclePlanComponent implements OnInit {
pageTitle: "Vehicle Plan";
_id : string = this.route.snapshot.params['id'];
public form: FormGroup;
plansElement = {}; sessionData = {}; activePlans = {}; activeMake = {}; loc = {}; city = {}; locationNames = {};
activePlanKey = []; activeMakeKey = []; locKey = []; cityKey = []; value = []; planVals = [];
securityDeposit : string ; fuleLevel : string; bookinH : string; bookingCycle : string; freeKm : string; grace : string; resVP: string;
planDetails: string; vehicleDetails: string; vehicleID: string; planID: string;
planName: string ; makeName : string;
constructor( private fb: FormBuilder,
private _sharedService: SharedService,
private router: Router,
private route: ActivatedRoute,
public snackBar: MdSnackBar,
public dialog: MdDialog,
private vpService: VehiclePlanService,
private plan: PlanService,
private locationService: LocationService,
private vmService: VehicleMakeService,
private commonService : CommonService
) {
this._sharedService.emitChange(this.pageTitle);
this.commonService.getSession().then((res) => {
this.sessionData = res['data'];
});
}
ngOnInit() {
this.getActivePlans();
this.getActiveVehicleMake();
this.getCityForPlan();
this.getLocForPlan();
this.planName= '' ; this.makeName = '';
this.form = this.fb.group({
plan_name: [null, Validators.required],
vehicle_make: [null, Validators.required],
rate_per_additional_km: [null, Validators.required],
rate_per_plan: [null, Validators.required],
planArray: this.fb.array([
this.initPlans([]),
])
})
}
// Operate vehiclemake to add / edit
actionVP(model: PlanInterface) {
let formData = model["value"];
var pa = model["value"].planArray;
for(let i=0; i<pa.length;i++) {
if(pa[i].location_name != null) {
let vp = {
'vehicle_make': [{
"id" : formData.vehicle_make,
"make_name" : this.vehicleDetails
}],
'plan_name': [{
"id" : formData.plan_name,
"plan_name" : this.planDetails
}],
'location': [{
"id" : "1",
"location_name" : pa[i].location_name,
"city" : pa[i].city,
"lat" : "0.00",
"long" : "0.00"
}],
'plan_rate': (pa[i].rate_plan != null) ? pa[i].rate_plan : formData.rate_per_plan,
'total_free_km': (pa[i].total_free_km != null) ? pa[i].total_free_km : this.freeKm,
'additional_km_charges': (pa[i].additional_km_charges != null) ? pa[i].additional_km_charges : formData.rate_per_additional_km,
'minimum_hours': (pa[i].minimum_hours != null) ? pa[i].minimum_hours : this.bookinH,
'booking_cycle': (pa[i].booking_cycle != null) ? pa[i].booking_cycle : this.bookingCycle,
'rate_fuel_level': (pa[i].rate_fuel_level != null) ? pa[i].rate_fuel_level : this.fuleLevel,
'grace_period': (pa[i].grace_period != null) ? pa[i].grace_period : this.grace,
'security_deposit': (pa[i].security_deposit != null) ? pa[i].security_deposit : this.securityDeposit,
"organization" : [{
"id" : "1",
"name" : "Driven"
}],
'modified_date': new Date()
};
// SAVE DATA START
if(this.route.snapshot.params['id']) {
this.updateVP(this.route.snapshot.params['id'], vp);
} else {
this.saveVP(vp);
}
// SAVE DATA END
}
}
}
// Insert data to vehiclemake
saveVP(vp) {
// Build data JSON
vp['created_date'] = new Date();
this.vpService.saveVehiclePlan(vp).then((result) => {
let id = result['data']['_id'];
this.openSnackBar("Saved vehicle plan successfully", "");
this.router.navigate(['/driven/vehicle-plan']);
}, (err) => {
this.openSnackBar("Something went wrong! vehicle plan not saved", "");
console.log(err);
});
}
// Update vehiclemake details
updateVP(id, vp) {
this.vpService.updateVehiclePlan(id, vp).then((result) => {
let id = result['data']['_id'];
this.openSnackBar("Updated vehicle plan successfully", "");
this.router.navigate(['/driven/vehicle-plan']);
}, (err) => {
this.openSnackBar("Something went wrong! vehicle plan not updated", "");
console.log(err);
});
}
// Get the all active plans
getActivePlans() {
this.plan.getActivePlans().then((res) => {
if(res['status'] == 'success'){
this.activePlans = res['data'];
this.activePlanKey = Object.keys(this.activePlans);
}else{
this.openSnackBar(res['data']['message'], "");
}
}, (err) => {
console.log(err);
});
}
// Get the all active plans
getActiveVehicleMake() {
this.vmService.getActiveVehicleMake().then((res) => {
if(res['status'] == 'success'){
this.activeMake = res['data'];
this.activeMakeKey = Object.keys(this.activeMake);
}else{
this.openSnackBar(res['data']['message'], "");
}
}, (err) => {
console.log(err);
});
}
// Get the all Locations for plans gruped by city
getCityForPlan() {
this.locationService.getCityForPlan().then((res) => {
if(res['status'] == 'success'){
this.city = res['data'];
this.cityKey = Object.keys(this.city);
}else{
this.openSnackBar(res['data']['message'], "");
}
}, (err) => {
console.log(err);
});
}
async getLocForPlan() {
let res = await this.locationService.getLocForPlan();
if(res['status'] == 'success') {
this.loc = res['data'];
this.locKey = Object.keys(this.loc);
this.addEditValues();
} else {
this.openSnackBar(res['data']['message'], "");
}
}
// used to display the alert message
openSnackBar(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
});
}
initPlans(planVals) {
//console.log(planVals);
return this.fb.group({
city_name: [planVals['city_name']],
city : [planVals['city']],
is_active: [planVals['is_active']],
location_name: [planVals['location_name']],
rate_plan: [planVals['rate_plan']],
total_free_km: [planVals['total_free_km']],
additional_km_charges: [planVals['additional_km_charges']],
minimum_hours: [planVals['minimum_hours']],
booking_cycle: [planVals['booking_cycle']],
rate_fuel_level: [planVals['rate_fuel_level']],
grace_period: [planVals['grace_period']],
security_deposit: [planVals['security_deposit']]
});
}
addEditValues() {
let len = this.locKey.length;
const control = <FormArray>this.form.controls['planArray'];
if(len) { control.removeAt(0); }
for(let i=0;i<len;i++) {
// DEFAULT NULL
this.planVals['city'] = null;
this.planVals['location_name'] = null;
this.planVals['is_active'] = null;
this.planVals['rate_plan'] = null;
this.planVals['total_free_km'] = null;
this.planVals['additional_km_charges'] = null;
this.planVals['minimum_hours'] = null;
this.planVals['booking_cycle'] = null;
this.planVals['rate_fuel_level'] = null;
this.planVals['grace_period'] = null;
this.planVals['security_deposit'] = null;
// DEFAULT NULL
this.planVals['city_name'] = this.loc[i]._id[0];
let lenInner = this.loc[i].locations.length;
for(let k=0;k<lenInner;k++) {
if(this.loc[i].locations[k].is_active) {
// UPDATED DATA FROM DB
if(this.planID && this.vehicleID) {
this.planVals['city'] = this.loc[i].locations[k].city[0];
this.planVals['location_name'] = this.loc[i].locations[k].location_name;
this.getVPDetails(this.planID,this.vehicleID,this.planVals['location_name'],this.planVals['city']).then((res: any) => {
console.log(res);
if(res['status'] == 'success') {
if(k==0) {
this.planVals['city_name'] = this.loc[i]._id[0];
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
}
// FROM DB
this.planVals['rate_plan'] = res['data'][0]['plan_rate'];
this.planVals['total_free_km'] = res['data'][0]['total_free_km'];
this.planVals['additional_km_charges'] = res['data'][0]['additional_km_charges'];
this.planVals['minimum_hours'] = res['data'][0]['minimum_hours'];
this.planVals['booking_cycle'] = res['data'][0]['booking_cycle'];
this.planVals['rate_fuel_level'] = res['data'][0]['rate_fuel_level'];
this.planVals['grace_period'] = res['data'][0]['grace_period'];
this.planVals['security_deposit'] = res['data'][0]['security_deposit'];
// FROM DB
this.planVals['city_name'] = null;
this.planVals['is_active'] = this.loc[i].locations[k].is_active;
this.planVals['city'] = this.loc[i].locations[k].city[0];
this.planVals['location_name'] = this.loc[i].locations[k].location_name;
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
} else {
if(k==0) {
this.planVals['city_name'] = this.loc[i]._id[0];
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
}
// BLANK DATA AT FIRST
this.planVals['rate_plan'] = null;
this.planVals['total_free_km'] = null;
this.planVals['additional_km_charges'] = null;
this.planVals['minimum_hours'] = null;
this.planVals['booking_cycle'] = null;
this.planVals['rate_fuel_level'] = null;
this.planVals['grace_period'] = null;
this.planVals['security_deposit'] = null;
// BLANK DATA AT FIRST
this.planVals['city_name'] = null;
this.planVals['city'] = this.loc[i].locations[k].city[0];
this.planVals['is_active'] = this.loc[i].locations[k].is_active;
this.planVals['location_name'] = this.loc[i].locations[k].location_name;
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
}
});
} else {
if(k==0) {
this.planVals['city_name'] = this.loc[i]._id[0];
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
}
// BLANK DATA AT FIRST
this.planVals['rate_plan'] = null;
this.planVals['total_free_km'] = null;
this.planVals['additional_km_charges'] = null;
this.planVals['minimum_hours'] = null;
this.planVals['booking_cycle'] = null;
this.planVals['rate_fuel_level'] = null;
this.planVals['grace_period'] = null;
this.planVals['security_deposit'] = null;
// BLANK DATA AT FIRST
this.planVals['city_name'] = null;
this.planVals['city'] = this.loc[i].locations[k].city[0];
this.planVals['is_active'] = this.loc[i].locations[k].is_active;
this.planVals['location_name'] = this.loc[i].locations[k].location_name;
control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY ####
}
}
}
}
}
removeFormArray() {
this.planVals = [];
const control = <FormArray>this.form.controls['planArray'];
for (var i = control.length - 1; i > 0; i--) {
this.removeInput(i);
}
}
removeInput(i: number) {
const control = <FormArray>this.form.controls['planArray'];
control.removeAt(i);
}
async getVPDetails(pid, vid, locname, cityname): Promise<any> {
return await this.vpService.getVehiclePlansInfo({plan_id: pid, make_id: vid, loc: locname, city: cityname});
}
// used to populate the default security deposit & fule level
selectVM(value){
this.vmService.showVehicleMake(value['value']).then((res) => {
this.securityDeposit = res['data']['base_security_deposit'];
this.fuleLevel = res['data']['rate_per_fuel_level'];
this.makeName = value['value'];
this.vehicleID = res['data']['_id'];
this.vehicleDetails = res['data']['brand_name'] + ' ' + res['data']['make_name'] + ' ' + res['data']['model_name'];
this.getVehiclePlan();
return false;
}, (err) => {
console.log(err);
});
}
// used to prepopulate the default value min booking h, h/ booking cycle, free km, grace time
//bookinH : string; bookingCycle : string; freeKm : string; grace : string;
selectPlan(value) {
this.plan.getPlansInfo(value['value']).then((res) => {
this.bookinH = res['data']['min_booking_hours'];
this.bookingCycle = res['data']['hours_per_booking_cycle'];
this.freeKm = res['data']['free_km_per_booking_cycle'];
this.grace = res['data']['grace_period_in_hours'];
this.planName = value['value'];
this.planDetails = res['data']['plan_name'];
this.planID = res['data']['_id'];
this.getVehiclePlan();
return false;
}, (err) => {
console.log(err);
});
}
// get the all plans on change of plans and vehicle make
getVehiclePlan(){
if(this.planName != '' && this.makeName != '' ) {
//const control = <FormArray>this.form.controls['planArray'];
//control.controls = [];
this.removeFormArray();
this.addEditValues();
}
}
// update the plan screen with default values
updateDefaultValue(){
var rate_plan = $('.rate_per_plan').val(); var additional_km_charges = $('.rate_per_additional_km').val();
var security_deposit = this.securityDeposit; var grace_period = this.grace;
var rate_fuel_level = this.fuleLevel; var booking_cycle = this.bookingCycle;
var minimum_hours = this.bookinH; var total_free_km = this.freeKm;
$('.security_deposit, .grace_period, .rate_fuel_level, .booking_cycle, .minimum_hours, .additional_km_charges, .total_free_km, .rate_plan').each(function(){
$('.security_deposit').val(security_deposit);
$('.grace_period').val(grace_period);
$('.rate_fuel_level').val(rate_fuel_level);
$('.booking_cycle').val(booking_cycle);
$('.minimum_hours').val(minimum_hours);
$('.additional_km_charges').val(additional_km_charges);
$('.total_free_km').val(total_free_km);
$('.rate_plan').val(rate_plan);
});
return false;
}
checkAllLoc(value){
var val = $('#'+value).val();
if(val == "true"){
$('.'+value).prop('checked', true);
$('#'+value).val("false");
} else {
$('.'+value).prop('checked', false);
$('#'+value).val("true");
}
}
uncheckParent(value){
$('#'+value).prop('checked', false);
$('#'+value).val("true");
}
}
我在 MeanStack 中使用 TypeScript 并使用带有 async 的函数,因为它没有按顺序工作
// Calling Function (In Main.ts file)
let rs = getVPDetails("2132");
// Function Definition (In Main.ts file)
async getVPDetails(pid) {
let res = await this.vpService.getPlansInfo({plan_id: pid});
return res;
}
// Middle Ware (IN service.ts file)
getPlansInfo(data) {
return new Promise((resolve, reject) => {
this.http.post('/vehicle-plan/plan-info', data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
我在返回 res 时(在“return res;”中)按照我的要求得到了准确的值。但是在 rs(我打电话的地方)中,我得到了这样的值:
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
在 __zone_symbol__value 中,我有我需要的数据,但我无法访问它。我知道我正在破坏 Promise 对象,但是当我不想在 getVPDetails() 中使用 then() 时,我该如何准确地解决它;
请让我知道我缺少什么或者我怎样才能获得我需要的数据。
提前致谢。
最佳答案
添加 async
后对于一个方法,它将总是返回一个Promise<T>
.在哪里T
无论你返回什么,string
, void
, w/e.
这就是 async
的全部思想, 获得正确值的唯一方法是使用 then
.你的async
这里实际上是没有必要的,因为你正在返回另一个 Promise
, 但那不是重点:)
最好使用类型提示,否则没有真正的理由使用 TypeScript
.这样,编译器会为您提供提示和错误,并且您会收到错误通知:
getVPDetails("2132").then((rs: PlanInfo) => {
// here you will have your `rs`
});
// Function Definition (using async/await as demonstration)
async getVPDetails(pid): Promise<PlanInfo> {
return await this.vpService.getPlansInfo({plan_id: pid});
}
// Middle Ware
getPlansInfo(data): Promise<PlanInfo> {
return this.http.post('/vehicle-plan/plan-info', data)
.map(res => res.json())
.toPromise();
}
关于angular - ExpressJS/Typescript - 无法检索 ZoneAwarePromise 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45615153/
基于此答案的问题:https://stackoverflow.com/a/18650183/4478897 我试图找到这个解决方案,但似乎没有任何效果符合我的需要。 集群 expressjs 和 so
我有一个使用 Sequelize.js 作为 ORM 运行的快速应用程序。我的 express 应用程序从我的主要 Rails 应用程序接收请求,并且由于跨域策略,这些请求是使用 getJSON 执行
如何处理同步错误并保证在同一代码中出现错误? 这是我的代码,但不确定其工作正常,有什么想法吗? helpers.list({ limit: 1 })
在我的 ExpressJS 代码中,我限制主体大小如下: app.use(bodyParser.urlencoded({ limit : "512kb", extended: fals
我有一个看起来像这样的对象: editinvite: { _id: '', title: '', codes_list: [] } 问题是我无法在 NodeJS 应用程序中访问codes_
我正在尝试让我的nodeapp 使用express 工作。 我已经通过 nginx 设置了反向代理以使用 https://dank.ml/api/v1但每当我启动我的应用程序时,它都不想检测 / 响应
我完全失去了理智: 我有一个快速应用程序:以下是此示例的几个文件的快照: 应用程序.js -模型 --Event.js --Match.js 路线 --matches.js app.js: globa
我有我的nodejs项目,我想将记录器与我的route.js分开以获得干净的代码。 但是我遇到了下一个问题,当我尝试将记录器加载到route.js 文件时,它会显示下一个错误: TypeError:
我在 MEAN 应用程序中的模板缓存方面遇到一些困难。我有一个导航栏,它使用条件逻辑来显示/隐藏向用户显示的按钮。当用户点击页面时,这些值将被设置为 null 或 false,但是一旦他们登录,这些值
是否可以根据可选路线创建不同的查询? app.get('/:genre/:book?', function (req, res) { var genre = req.params.genre; v
我正在尝试学习 ExpressJS,并且遇到了这段代码。我似乎无法理解 app.use 函数,并且文档对我来说也不清楚。当调用 app.use 时,此特定示例代码中的/public 目录到底发生了什么
我正在开发一个学校管理系统。当老师发送发布请求时,我在后端创建一个路由内的全局对象。所以当多个老师访问服务器时,会创建多个全局对象......或者每个老师访问同一个对象?(会被重写同一个对象吗?) 最
我有一个用 typescript 编写的小型微服务,在 AKS 上的 kubernetes 集群中运行。我使用 Helm 生成了入口 apiVersion: extensions/v1beta1 ki
我需要将 JSON 发送到我的服务器,但 POST 请求显示为空正文。这是我在前端的 typescript : function sendData() : void { console.log("Se
这是我的 app.js import path from 'path'; import bodyParser from 'body-parser'; import express from 'expr
我一直在使用 ExpressJS 来促进文件上传,但据我所知,您可以将文件上传到任何路由,无论它是否处理它。 说我有 app.post('/photos/upload', photos.upload)
我正在阅读 Express.JS 4.x API,并且很好奇他们是如何设置的。这是我对正在发生的事情的理解:在 Express.JS 4.x API 的示例代码中,express 模块被导入并分配给变
我有以下注册页面 form(method='post', action='users/register') .form-group label Name inp
我有诸如 :id/comments/、:id/otherRoute 等路线。对于这些路线,我需要创建新的 Controller 。例如: let id: number = +req.params["i
嘿,我有一个使用 Express.js 和 Handlebars 运行的网站,该网站的导航栏和侧边栏在所有页面上都保持相同。当我路由时,它仅更改页面容器 {{{body}}}。 有没有一种方法可以让我
我是一名优秀的程序员,十分优秀!