Angular2 - 同步方法调用(TypeError:this.customer未定义)

时间:2017-04-14 10:13:45

标签: angular asp.net-web-api synchronization

我的申请表有问题:

经常发生的代码与api调用没有同步:

服务方法

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;
  }
带有方法调用的

组件

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]);
  }
}

情况如下:

在第一次调用 do_CustomerInitialize 时,正确调用了Api,但在此行代码中出现了Javascript运行时错误:

alert(this.customer.idCustomer);    //GENERATE ERROR

TypeError:this.customer未定义

我第二次调用该函数,一切正常,再次调用api,警报为我提供了idCustomer值......

我认为这是同步/异步通话问题。

我该如何避免这个问题? 我必须在我有idCustomer定价的时候路由应用程序...

感谢支持 侨

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

1)将subscribe块从服务移动到组件,以便您的服务返回Observable:

Initialize(_idUser: number,_BusinessName: string, _VAT: string, _FiscalCode: string): Observable<Customer> {

  var req: ReqCustomerInitialize = {
    idUser: _idUser,
    BusinessName: _BusinessName,
    VAT: _VAT,
    FiscalCode: _FiscalCode
  };

  return this.http.post(this.baseUrl + "initialize", req, this.getRequestOptions)
    .map(response => response.json())
    .catch(this.handleError);
}

2)在组件内的subscribe内执行逻辑:

do_CustomerInitialize(e) {
  e.preventDefault();

  var _BusinessName = this.FormCustomerCreate.value.BusinessName;
  var _VAT = this.FormCustomerCreate.value.VAT;
  var _FiscalCode = this.FormCustomerCreate.value.FiscalCode;

  this.customerService.Initialize(0,_BusinessName,_VAT,_FiscalCode)
    .subscribe(data => {
      this.customer = data;
      alert(this.customer.idCustomer);
      this.router.navigate(['CustomerDetail', this.customer.idCustomer]);
    }
}

答案 1 :(得分:1)

初始化函数应该返回observable。

Initialize(_idUser: number,_BusinessName: string, _VAT: string, _FiscalCode: string): Customer {

    var req: ReqCustomerInitialize = {
      idUser: _idUser,
      BusinessName: _BusinessName,
      VAT: _VAT,
      FiscalCode: _FiscalCode
    };

    return this.http.post(this.baseUrl + "initialize", req, this.getRequestOptions)
      .map(response => response.json())
  }

然后在你的组件中

    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).subscribe(( => {
                alert(this.customer.idCustomer);    //GENERATE ERROR
                this.router.navigate(['CustomerDetail',this.customer.idCustomer]);
            }));
     }

但我认为你正在寻找BehaviorSubject。这是示例

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { User } from './user';

@Injectable()
export class UserService {
    user: BehaviorSubject<User>;

    constructor(private http:Http) {
        this.user = new BehaviorSubject(new User({}));
    }

    public init() {
        this.http.get(window['Routing'].generate('api_v1_user_get_profile'))
            .map(response => response.json())
            .subscribe(user => {
                    this.user.next(new User(user['data']));
                }
            );
    }

    getUser() {
        if (!(this.user instanceof User)) {
            this.init();
        }
        return this.user.asObservable();
    }
}

这里有更多信息http://www.developersite.org/101-218532-angular2