【问题标题】:Get data from subscribe function in local variable angular 6从局部变量 angular 6 中的订阅函数获取数据
【发布时间】:2018-07-30 02:43:11
【问题描述】:

这是我在 app.service.ts 中使用 post 的 api 调用

userinsert(user:User,cart:Cart[])
{

    var databaseinput={user:user,cart:cart};
  return  this.http.post("http://localhost:3000/api/payment",databaseinput);

}

这是我的 cart.component.ts 我在这里使用订阅来获取这样的数据

export class CartComponent{
    mydata:string;
myfuncto(){
    this.appservice.userinsert(user,currentcart).subscribe(
      data => {this.mydata=data// want to do something like this
      },
      error => { console.log(error); // Error if any
      },
      ()=> {}

    )
console.log(mydata) //it should print the data
}
}

但是它给了我错误类型 object is not assignable to type string ,我使用了 data.json() 但没有成功,知道怎么做吗??

【问题讨论】:

    标签: angular


    【解决方案1】:

    由于响应是一个对象,请将您的 mydata 变量更改为对象类型或任何类型

    mydata:any;
    

    console.log 也应该在订阅中,因为请求是异步的,否则它将是未定义的。

    【讨论】:

    • 如何在外部函数中使用??
    • 您需要有另一个函数并将值传递给订阅内的函数。标记是否有帮助
    猜你喜欢
    • 2019-09-15
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多