I have a problem in my application:
Often happens that the code is not sinchronized with the api call:
service method
Initialize(_idUser: number,_BusinessName: string, _VAT: string, _FiscalCode: string): Customer {
var req: ReqCustomerInitialize = {
idUser: _idUser,
BusinessName: _BusinessName,
VAT: _VAT,
FiscalCode: _FiscalCode
};
var x = this.http.post(this.baseUrl + "initialize", req, this.getRequestOptions)
.map(response => response.json())
.catch(this.handleError)
.subscribe(data => {
this._customer = data;
}
);
return this._customer;
}
component with method call
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from "@angular/forms";
import { AuthService } from "../services/auth.service";
import { CustomerService } from "../services/customer.service";
import { Router } from "@angular/router";
import { Customer } from '../model/customer';
@Component({
selector: 'app-customer-initialize',
templateUrl: './customer-initialize.component.html',
styleUrls: ['./customer-initialize.component.css']
})
export class CustomerInitializeComponent implements OnInit {
title = "Initialize";
FormCustomerCreate = null;
ErrorOffertCreate = false;
customer: Customer;
constructor(
private customerService: CustomerService,
private fb: FormBuilder,
private router: Router,
private authService: AuthService) {
if (!this.authService.isLoggedIn()) {
this.router.navigate([""]);
}
this.FormCustomerCreate = fb.group({
BusinessName: ["", Validators.required],
VAT: ["", Validators.maxLength(30)],
FiscalCode: ["", Validators.maxLength(30)]
});
}
ngOnInit() {
}
do_CustomerInitialize(e) {
e.preventDefault();
var _BusinessName = this.FormCustomerCreate.value.BusinessName;
var _VAT = this.FormCustomerCreate.value.VAT;
var _FiscalCode = this.FormCustomerCreate.value.FiscalCode;
this.customer = this.customerService.Initialize(0,_BusinessName,_VAT,_FiscalCode);
alert(this.customer.idCustomer); //GENERATE ERROR
this.router.navigate(['CustomerDetail', this.customer.idCustomer]);
}
}
The situation is this:
On fist call of do_CustomerInitialize, the Api is properly called but I get Javascript runtime error in this line of code:
alert(this.customer.idCustomer); //GENERATE ERROR
TypeError: this.customer is undefined
The second time that I call the function, all works, the api is called again and the alert provides me the idCustomer value...
I think that it is a Sync/Async call problem.
How can I avoid this problem? I have to route the application only when I have the idCustomer valorized...
Thanks to support Ciao