typescript Angular 7 - HttpClient“类型对象上不存在属性‘成功’”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53824063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:44:30  来源:igfitidea点击:

Angular 7 - HttpClient "Property 'success' does not exist on type Object"

angulartypescript

提问by Brian

When someone registers, I post the info to my back-end. When successfully registering a user, I get a json response back of {success: true, msg: "User registered"}. My problem is when I try to do an if statement to check if success is set to true.

当有人注册时,我会将信息发布到我的后端。成功注册用户后,我收到 {success: true, msg: "User Registration"} 的 json 响应。我的问题是当我尝试执行 if 语句来检查成功是否设置为 true 时。

Here is my code that isn't working:

这是我的代码不起作用:

    // Register User
    this.apiService.registerUser(user).subscribe(data => {
      if(data.success) {
        this.flashMessage.show('Registration successful', { cssClass: 'alert-success', timeout: 3200 });
      } else {
        this.flashMessage.show('Registration failed', { cssClass: 'alert-danger', timeout: 3200 });
      }
    });


I was able to console.log the response of data, and it returned:

我能够 console.log 数据的响应,它返回:

{success: true, msg: "User registered"}


Here is the code from my ApiService:

这是我的 ApiService 中的代码:

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

import { User } from '../models/User';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private baseUri: string = 'http://localhost:5000/api';
  private headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  registerUser(user: User) {
    return this.http.post(this.baseUri + '/register', user, { headers: this.headers });
  }
}


Here is the code from my Register Component:

这是我的注册组件中的代码:

onRegisterSubmit() {
    const user: User = {
      firstName: this.firstName,
      lastName: this.lastName,
      email: this.email,
      username: this.username,
      password: this.password
    };

// Register User
    this.apiService.registerUser(user).subscribe(data => {
      console.log(data);
    });

  }

Screenshot of error from ng serve

ng serve 错误截图

I'm quite new to working with angular let alone a back-end, so if you could explain why this error was occurring it would be greatly appreciated.

我对使用 angular 还很陌生,更不用说后端了,所以如果你能解释为什么会发生这个错误,我将不胜感激。

Please let me know if you need any more information.

如果您需要更多信息,请告诉我。

回答by joh04667

This is a compiler error, and it's one of the reasons Typescript is awesome!

这是一个编译器错误,这也是 Typescript 很棒的原因之一!

Your registerUsermethod's return type is implicitly an Object(or {}) because that's what http.postis returning. http.postaccepts a generic parameter to define what will be coming back in the response's body. Without that parameter, it will return type {}(because, without some sort of definition, JSON is just an unknown Object)... and a key of successdoes not exist on {}.

您的registerUser方法的返回类型隐式是Object(or {}),因为这http.post就是返回的内容。http.post接受一个通用参数来定义将在响应的body. 如果没有该参数,它将返回类型{}(因为,没有某种定义,JSON 只是一个 unknown Object)...并且 的键success不存在于{}

Assuming you have a fleshed out response object, just strongly type it:

假设你有一个充实的响应对象,只需强烈输入它:

interface UserPostResponse {
  success: boolean
}

...

  registerUser(user: User): Observable<UserPostResponse> {
    return this.http.post<UserPostResponse>(this.baseUri + '/register', user, { headers: this.headers });
  }

Conversely, if you wanted the HttpRequestitself and not the body, you just have to tell the HttpClientwhat part of the response to observe:

相反,如果你想要它HttpRequest本身而不是身体,你只需要告诉HttpClient观察响应的哪一部分:

  registerUser(user: User): Observable<HttpResponse<object>> {
    return this.http.post(this.baseUri + '/register', user, { headers: this.headers }, observe: 'response');
  }

...and HttpResponsehas a status, statusText, body, etc.

...并且HttpResponse有一个status, statusText, body, 等等。

回答by muradm

error TS2339: Property 'x' does not exist on type 'Y'

错误 TS2339:类型“Y”上不存在属性“x”

Is compile time error. Angular HttpClienthas various postfunction declarations, one of which is:

是编译时错误。AngularHttpClient有多种post函数声明,其中之一是:

post<T>(url: string, body: any | null, options?: { ... }): Observable<T>;

Where you can strongly type your type of response. You can introduce response interface and use it like:

您可以在其中强烈输入您的响应类型。您可以引入响应接口并使用它:

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

import { Observable } from 'rxjs';

import { User } from '../models/User';

export interface RegisterResponse {
  success: boolean;
  msg: string;
}

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private baseUri: string = 'http://localhost:5000/api';
  private headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  registerUser(user: User): Observable<RegisterResponse> {
    return this.http.post<RegisterResponse>(this.baseUri + '/register', user, { headers: this.headers });
  }
}

Then you will be type safe from TypeScript compiler perspective.

然后,从 TypeScript 编译器的角度来看,您将是类型安全的。

Otherwise, matched declaration will be:

否则,匹配的声明将是:

post(url: string, body: any | null, options?: { ... }): Observable<Object>;

Where Objecthas no declared property succuess, thus will cause that error.

WhereObject没有声明的属性succuess,因此会导致该错误。

Another way to avoid it is to use as anyor any, see references below. But normally, you would want TypeScript to track your types.

另一种避免它的方法是使用as anyor any,请参阅下面的参考资料。但通常情况下,您会希望 TypeScript 跟踪您的类型。

TypeScript is strongly typed, meaning that it will attempt to make sure that data types your are using are actually correct. So if you are trying to refer to some property which has no known type, it will complain.

TypeScript 是强类型的,这意味着它会尝试确保您使用的数据类型实际上是正确的。因此,如果您尝试引用某个没有已知类型的属性,它会抱怨。

You may see also:

您可能还会看到:

And so on to understand the matter.

等等就明白了。

回答by Mishan Madhupa

Property 'success' does not exist on type 'Object'. Create code as:

类型“对象”上不存在属性“成功”。创建代码为:

// Register User
this.apiService.registerUser(user).subscribe( (data) => {
    if(data['success']) {
        this.flashMessage.show('Registration successful', { cssClass: 'alert-success', timeout: 3200 });
    } else {
        this.flashMessage.show('Registration failed', { cssClass: 'alert-danger', timeout: 3200 });
    }
});

This change correct my error in Angular tsfile.

此更改更正了我在 Angular ts文件中的错误。