首页 > 解决方案 > 为什么在浏览器中显示订阅未定义

问题描述

  updload(name,age,address)
  {
    debugger;
    this.data=this.service.tryinsert(name,age,address);
    this.data.subscribe(
     (respose:any)=>{
        console.log(respose);
      }
    )
  }
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

我已经导入了上述两个文件,但是当我从浏览器传递姓名、年龄、地址的数据时,它说

错误类型错误:无法读取未定义的属性“订阅”

标签: undefinedangular8subscribe

解决方案


问题说

错误类型错误:无法读取未定义的属性“订阅”

因为到this.data.subscribe()被调用的时候,变量this.data还没有被赋值。

服务函数几乎总是在角度上是可观察的,因此是异步的。这意味着服务器的响应将取决于几个因素,而不是瞬时的。

要更正您的代码,您可以像下面这样使用它:

updload(name,age,address)
  {
    debugger;
    this.service.tryinsert(name,age,address)
        .subscribe(responseData => {
            console.log(responseData);
            // use the code below if responseData is not of type string
            // console.log(JSON.stringify(responseData));
    });

   }

推荐阅读