【问题标题】:object undefined in second part of the form表单第二部分中未定义的对象
【发布时间】:2019-04-05 17:45:44
【问题描述】:

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

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

但是,当我在提交表单的第二部分时 console.log 它。我收到一个未定义的错误。我做了这个对象的 ID 发送到 URL。

广告服务

  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的控制台数据

知道这里有什么问题吗?

完整的 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);
      });
    }
  }

}

【问题讨论】:

  • 请分享更多关于您的模态的详细信息以及您在这里谈论的是什么属性?
  • 添加了模型。财产=房子/公寓。这是一个房地产网站
  • 所以你的意思是 console.log(this.payment); 未定义?
  • 工作正常。在顶部的第二个代码块中。 console.log(currentProperty) 未定义。
  • 似乎返回currentProperty 的服务正在返回一个未定义id 的对象。 id 是可选的 因为它被声明为id?:(问号表示它是可选的),所以你不能依赖它在那里。确保服务返回您所需要的一切。

标签: javascript json angular typescript


【解决方案1】:

所以看到代码,您似乎从未在组件中订阅 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
     });
  }

在 Angular 中,http 请求返回 observable,所以你需要 subscribe。如果observable 没有任何订阅者,不会执行

【讨论】:

  • OP 必须在某个地方订阅该函数,因为它们正在显示结果的控制台日志。问题只是不完整,我们不知道这个函数在哪里调用...
  • @AJT_82,是的,你是对的。我们无法确定他是否分享了最小的、可重现的示例。
猜你喜欢
  • 2021-03-18
  • 2015-09-06
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多