表单第二部分中未定义的对象

时间:2019-04-05 17:45:44

标签: javascript json angular typescript

当我说财产时,我指的是房屋。它是一个房地产网站。

我正在使用Angular(后端的Laravel API)创建一个应用程序。我有3个步骤来提交财产。在广告服务的第一步中,我将当前属性设置为返回的模型数据。我可以用console.log记录这些数据。

但是,当我在提交表单第二部分时进行console.log记录时。我收到未定义的错误。我从该对象获取ID并将其发送到URL。

AdvertService

  createAdvert(userId: number, property: Property) {
    return this.http.post(this.baseUrl + userId + '/store', {property}).pipe(
      map((response: any) => {
          this.currentProperty = response;
          console.log(response);
      })
    );
  }

我将服务注入到表单的第二部分。我尝试调用当前属性并进行console.log记录,但未定义。

  submitPayment() {
    const currentProperty = this.advertService.currentProperty.id;
    console.log(currentProperty);
    if (this.advertPaymentForm.value) {
      this.payment = (Object.assign({}, this.advertPaymentForm.value));
      console.log(this.payment);
      this.advertService.createAdvertPayment(currentProperty.id, this.payment).subscribe(data => {
        this.alertify.success('Success');
      }, error => {
        this.alertify.error(error);
      });
    }
  }

属性模型

export interface Property {
    id?: number;
    town?: string;
    county?: string;
    address: string;
    postocde: string;
    eircode: string;
    property_type: string;
    selling_type: string;
    price: number;
    bedrooms: number;
    bathrooms: number;
    size: number;
    building_energy_rating: string;
    description: string;
    user_id: number;
}

编辑。 createAdvert的控制台数据

Image

您知道这里的问题是什么吗?

完整的advert.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Property } from '../_models/property';
import { User } from '../_models/user';
import { Payment } from '../_models/payment';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AdvertService {

  baseUrl = environment.apiUrl + 'advertisement/';
  currentProperty: any;

  constructor(private http: HttpClient) { }

  createAdvert(userId: number, property: Property) {
    return this.http.post(this.baseUrl + userId + '/store', {property}).pipe(
      map((response: any) => {
          this.currentProperty = response;
          console.log(this.currentProperty);
      })
    );
  }

  createAdvertPayment(propertyId: number, payment: Payment) {
    return this.http.post(this.baseUrl + propertyId + '/payment', {payment});
  }
}

完整的advert-payment.component.ts(将服务注入到其中)

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { AdvertService } from '../_services/advert.service';
import { AlertifyService } from '../_services/alertify.service';
import { AuthService } from '../_services/auth.service';
import { Payment } from '../_models/payment';

@Component({
  selector: 'app-advert-payment',
  templateUrl: './advert-payment.component.html',
  styleUrls: ['./advert-payment.component.css']
})

export class AdvertPaymentComponent implements OnInit {
  advertPaymentForm: FormGroup;
  model: any;
  payment: Payment;
  constructor(private advertService: AdvertService, private alertify: AlertifyService, public authService: AuthService,
    private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createAdvertPaymentForm();
  }

  createAdvertPaymentForm() {
    this.advertPaymentForm = this.formBuilder.group({
      town: ['', Validators.required],
      county: ['', Validators.required],
      billing_address: ['', Validators.required],
      cardnumber: ['', Validators.required],
      month: ['', Validators.required],
      year: ['', Validators.required],
      cvv: ['', Validators.required],
    });
  }

  submitPayment() {
    const currentProperty = this.advertService.currentProperty[0].id;
    console.log(currentProperty);
    if (this.advertPaymentForm.value) {
      this.payment = (Object.assign({}, this.advertPaymentForm.value));
      console.log(this.payment);
      this.advertService.createAdvertPayment(currentProperty.id, this.payment).subscribe(data => {
        this.alertify.success('Success');
      }, error => {
        this.alertify.error(error);
      });
    }
  }

}

1 个答案:

答案 0 :(得分:0)

因此,看到它出现的代码,您就从未在组件中订阅createAdvert(userId: number, property: Property),因此currentProperty从未从HTTP调用中获取值。

请确保在您的组件OnInit中预订:

ngOnInit() {
    this.createAdvertPaymentForm();
    this.advertService.createAdvert(YourUserId, UserProperty).subscribe(data => {
         console.log(data); // this will give you `currentProperty` data
     });
  }
  

在成角度的情况下,http请求返回可观察到的,因此您需要进行subscribe。如果observable没有订阅者,则该订阅将不会执行