【问题标题】:Typescript async and this scope打字稿异步和这个范围
【发布时间】:2021-06-17 11:03:49
【问题描述】:

我已经设置了一个简单的服务来从数据库中提取数据,该服务工作正常,但是当我尝试通过 aysnc 函数从服务中获取数据并进入组件时,我似乎无法通过通过使用“this”来定义函数的范围。

有什么想法吗?由于我是开发新手,所以我肯定做错了什么。

这是运行良好的服务代码;

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) { }

  httpGetFeatures() {
    console.log("inFeatures")
    this.http.post("http://******************",
  {
         "command": "get_feature",
         "classes":"F,G"
  })

  .subscribe(
         (val) => {
        console.log("inSubscribe")
        console.log(val)
          return(val)
          //this.parseFeatures(val)
         },
         response => {
         console.log("POST call in error", response);
         },
                 () => {
  });
  }



  parseFeatures (val: any) {
    console.log("in parse Features")
    console.log(val)
  }



}

这里是组件 TS,问题是“this”会引发错误,因为它是未定义的,因为我相信 this 的范围没有被传递。它是底部的最终异步函数。

import { Component, OnInit } from '@angular/core';
import * as data from "./testfile.json";
import * as catdata from "../categories/cattestfile.json";
import {VenueserviceService} from "../../services/venueservice.service"


@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor(private venueService: VenueserviceService) { }

  panelOpenState = false;
  title = 'Cotswolds Destinations';

  venues: any = (data as any).default;

  categories: any = (catdata as any).default;

  formatLabel(value: number) {
    if (value >= 1000) {
      return Math.round(value / 1000) + 'm';
    }

    return value;
  }

  value = 'Clear me!';

  ngOnInit(): void {
    console.log("Homepage Start");
    console.log(this.categories);
    console.log(this.venues);
    console.log(data);
    console.log(this.venues.name);
    for(var i=0; i < this.venues.length; i++){
    console.log(this.venues[i]);
    }
    console.log("Homepage End");
    let categories = this.venueService.httpGetFeatures()

    console.log(categories)

  }
}



const getData =  async () => {
  const data  = await this.venueService.httpGetFeatures()
  console.log(data)
}

【问题讨论】:

  • 只是一个 FIY,不要将实际链接发布到您的 API 端点 :-)
  • @monstertjie_za 我下次不会了,谢谢:/ 指出来!

标签: javascript angular typescript asynchronous angular-material


【解决方案1】:

我建议你这样做

服务文件

    httpGetFeatures() {
        console.log("inFeatures")
        return this.http.post("http://cotswoldsdestinations.co.uk:8443",
        {
            "command": "get_feature",
            "classes":"F,G"
        })
    }

组件文件

fetchedData:any;
const getData =  async () => {
  this.venueService.httpGetFeatures()
    .subscribe( data => { this.fetchedData = data });
}

【讨论】:

  • 这是一个很好的建议,但它仍然不起作用,“any”会引发错误,因为它被用作值而不是类型。 “数据”错误,因为它具有“任何”类型。 'this' 仍然没有通过,它是错误的,因为它是一个未定义的对象。用头撞墙大声笑
  • 你能粘贴实际的堆栈跟踪吗?这到底是什么意思没有通过。 “this”是一个关键字。您不能在函数中传递关键字。您可以编辑问题并粘贴错误的实际堆栈跟踪,以便人们更好地理解它
【解决方案2】:

第一,你在VenueserviceService.httpGetFeatures中没有返回任何东西,它的返回类型是void。

第二,由于您使用的是 asyc-await 语法,因此您期望在 getData lambda 函数中有一个承诺。要么这样做:

httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  }).toPromise();
}

或者直接订阅返回的 observable 而不等待:

httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  });
}
const getData = () => {
  this.venueService.httpGetFeatures().subscribe(data =>
    console.log(data);
  );
}

如果您在某个组件中定义了getData,并且在其构造函数中通过 DI 传递了venueService: VenueserviceService,这一切都可以。

要使其正常工作,请将 getData 定义为主页组件类的成员,例如:

export component HomePageComponent {
  constructor(private venueService: VenueserviceService) {}

  getData() {
    this.venueService.httpGetFeatures().subscribe(data =>
      console.log(data);
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2019-10-16
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多