【问题标题】:Property 'success' does not exist on type 'Object'“对象”类型上不存在属性“成功”
【发布时间】:2019-08-14 18:32:26
【问题描述】:

user.js

router.post('/register', (req, res) => {
let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
});

User.addUser(newUser, (err, user) => {
    if (err) {
        res.json({ "success": false, msg: 'Failed to register User' })
    } else {
        res.json({ "success": true, msg: "User Added" })
    }
})
});

authservice.ts

import { catchError,map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import {HttpClient,HttpHeaders,HttpErrorResponse} from '@angular/common/http';

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

  constructor(private http:HttpClient) { }

  registerUser(user){
    let headers = new HttpHeaders();
    headers.append('content-type','application/json');

return this.http.post('http://localhost:8080/users/register',user, 
        {headers:headers})
  }
 }

register.component.ts

import { ValidateService } from './../../services/validate.service';
import { Component, OnInit } from '@angular/core';
import { FlashMessagesService } from 'angular2-flash-messages';
import {AuthService} from '../../services/auth/auth.service';
import {Router } from '@angular/router';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  name:String;
  username:String;
  email:String;
  password:String;

  constructor(private _validate:ValidateService,
    private _flashMessagesService: FlashMessagesService,
    private _authservice:AuthService,
    private _router:Router) { }

  ngOnInit() {
  }

  onRegisterSubmit(){
const user={
  name:this.name,
  username:this.username,
  email:this.email,
  password:this.password,
}
this._authservice.registerUser(user)
  .subscribe(data =>{
    console.log(data);
    **if(data.success){**
      this._flashMessagesService.show('Registration Succesfull ! ',{cssClass:'alert-success',timeout:3000})
      this._router.navigate(['/login']);
    }else{
      this._flashMessagesService.show('Oops Something went wrong! ',{cssClass:'alert-danger',timeout:3000})
      this._router.navigate(['/register'])
    }
  })
 }
}

错误

src/app/components/register/register.component.ts(49,17) 中的错误:错误 TS2339:“对象”类型上不存在属性“成功”。

数据成功提交,甚至角度也成功重定向到下一个组件,但这会出错。在 register.component.ts 中同时订阅 if 语句中返回对象的属性 success if(data.success)

【问题讨论】:

    标签: node.js angular http mongoose mean-stack


    【解决方案1】:

    您可以使用以下代码:

    dataRegister:any={}
    
    //Function register
    this._authservice.registerUser(user)
      .subscribe(data =>{
        
        this.dataRegister = data;
        if(this.dataRegister.success){
          //
        }
        else{
          //
        }
      
     }

    【讨论】:

      【解决方案2】:

      您可以对您的回复使用类型检查来避免此类错误。

      创建一个包含 HTTP 响应结构的 RegisterResponse 类。

      export class RegisterResponse {
        public success: boolean;
        public msg: string;
      }
      

      然后将其作为通用参数传递给您的 http.post() 方法:

      import { RegisterResponse } from './RegisterResponse'; // Or wherever it is..
      
      export class AuthService {
      
        constructor(private http:HttpClient) { }
      
        registerUser(user){
          let headers = new HttpHeaders();
          headers.append('content-type','application/json');
      
          return this.http.post<RegisterResponse>('http://localhost:8080/users/register', user, {headers:headers});
        }
      }
      

      registerUser() 方法将返回Observable&lt;RegisterResponse&gt; 类型,因此当您订阅它时,您的data 变量将是RegisterResponse 类型。但你也可以根据需要指定类型:

      this._authservice.registerUser(user)
        .subscribe((data: RegisterResponse) => {
          if (data.success) {
            // ...
          }
          else {
            // ...
          }
        });
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2019-05-18
        • 1970-01-01
        • 2019-10-11
        • 2018-02-10
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-23
        相关资源
        最近更新 更多