属性“”在类型“对象”上不存在

时间:2019-11-27 19:11:57

标签: javascript node.js angular typescript npm

我整天都在努力工作。一整天一切都很好。
重新启动服务器(ng服务)。现在突然出现了很多错误。
我设法解决了大多数问题,但我坚持使用了它。

running ng serve

这是组件.ts文件的主要部分:

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-playboard',
  templateUrl: './playboard.component.html',
  styleUrls: ['./playboard.component.scss']
})
export class PlayboardComponent implements OnInit {
  brews: Object;

  constructor(private _http: HttpService) { }

  ngOnInit() {
    this._http.myMethod().subscribe(data => {
      this.brews = data;
      this.dices = this.brews.myBox;
      this.diceSeed = this.brews.boxID;
      console.log(this.brews);
    });
  }

这是http.service.ts文件:

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

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

  constructor(private http: HttpClient) { }

  myMethod() {
    return this.http.get<Object>('https://localhost:44398/api/boggle');
  }

  myWordMethod(word) {
    var url = 'https://localhost:44398/api/wordpoints/' + word;
    return this.http.get<Object>(url);
  }
}

整天都在工作,突然出现了这些奇怪的错误。
有谁知道可能出什么问题了吗?非常感谢!

2 个答案:

答案 0 :(得分:0)

您只需忽略它们为any类型就可以忽略它们。例如;

myWordMethod(word: any) {
    ..
}

this._http.myMethod().subscribe(data: any => {
    ..
});

话虽如此,通常首选声明TypeScript的实际类型。对于实例,如果您的API发送回具有特定属性的通用对象,则将其声明为这样;

interface MyMethodResponse {
    someProperty: string;
    someNumber: number;
    someArray: string[];
}

this._http.myMethod().subscribe((myMethodResponse: MyMethodResponse) => {
    // TypeScript now knows that these properties exists on the response object
    console.log(myMethodResponse.someArray);           
    console.log(myMethodResponse.someNumber); 
    console.log(myMethodResponse.someProperty); 
});

答案 1 :(得分:0)

从您的http调用中删除对象。使用泛型是可选的,特别是如果您没有输入响应的话。

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

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

  constructor(private http: HttpClient) { }

  myMethod() {
    return this.http.get('https://localhost:44398/api/boggle');
  }

  myWordMethod(word) {
    var url = 'https://localhost:44398/api/wordpoints/' + word;
    return this.http.get(url);
  }
}

在啤酒上,将其声明为任意

import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-playboard',
  templateUrl: './playboard.component.html',
  styleUrls: ['./playboard.component.scss']
})
export class PlayboardComponent implements OnInit {
  brews: any;

  constructor(private _http: HttpService) { }

  ngOnInit() {
    this._http.myMethod().subscribe(data => {
      this.brews = data;
      this.dices = this.brews.myBox;
      this.diceSeed = this.brews.boxID;
      console.log(this.brews);
    });
  }