简体   繁体   English

Angular 6 Observable和subscribe

[英]Angular 6 Observable and subscribe

I have some data in angular services coming from REST API 我有来自REST API的角度服务中的一些数据

info.services.ts info.services.ts

getCustomerDetails() {
   this.http.get(this.localUrl + this.customerUrl + this.options).pipe(map((response: Response) => response.json()))
}

my homepage.ts 我的主页

getData(){
  this.infoServices.getCustomerDetails().subscribe(data=>{
    if(data) {
      this.name = data[0].customerInfo.name;
    }
  })
}

and my home.html 和我的home.html

<input type="text" value="{{this.name}}" formControlName="name" />

my question is there any better way to fetch data instead of doing data[0]? 我的问题是有没有更好的方法来获取数据而不是数据[0]?

endpoint: 终点:

router.post("/request/customer", (req, res) => {
    var pendingRequest = new Customer({
        name: req.body.name,
        age: req.body.age,
        isNewCustomer: true,
        requestInfo: {
            customerType: req.body.customerType,
            sendTo: {
                email: req.body.sendTo_email,
                company: req.body.sendTo_company
            },
            returnTo: {
                email: req.body.returnTo_email,
                company: req.body.returnTo_company
            }
        },
    });
    pendingRequest
        .save()
        .then(result => {
            console.log(result);
            res.status(200).json({
                message: "Handling POST request to /pending",
                createdRequest: result
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            });
        });

You can do it in your service it the map function : 您可以在服务中执行地图功能:

   this.http.get(url).pipe(map((response: Response) => response[0])

This way when you subscribe to your observabla the date retrieved will be available directly 这样,当您订阅observabla时,检索的日期将直接可用

You would also want to create an interface that defines the structure of your response so that you can manipulate your objects easily 您还需要创建一个定义响应结构的界面,以便您可以轻松地操作对象

I have found the solution, so in ts file: 我找到了解决方案,所以在ts文件中:

customerData:any = []
    getData(){
    this.customerData = [];
      this.infoServices.getCustomerDetails().subscribe(data=>{
        if(data) {
          this.customerData = data;
        }
      })
    }

and in your html template simply 并在您的HTML模板中

<div *ngFor="let data of customerData; let i = index">
{{data.name}}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM