簡體   English   中英

“對象”不包含此類成員Angular 5

[英]'object' does not contain such a member Angular 5

我是Angular的新手,正在嘗試制作一個小型應用程序。

我提到的“對象”不包含這樣的成員答案,但我沒有從那里得到解決方案。

profile.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  user: Object;
  constructor(private authService: AuthService, private roter: Router) {}

  ngOnInit() {
    this.authService.getProfile().subscribe(
      profile => {
        this.user = profile.user;
      },
      err => {
        console.log(err);
        return false;
      }
    );
  }
}

profile.component.html

<div *ngIf="user">
  <h2 class="page-header">
    {{ user.name }}
  </h2>
  <ul class="list-group">
    <li class="list-group-item">
      Username: {{ user.username }}
    </li>
    <li class="list-group-item">
      Email: {{ user.email }}
    </li>
  </ul>
</div>

Visual Studio代碼顯示此錯誤:

[角度]標識符“用戶名”未定義。 “對象”不包含此類成員

ProfileComponent的屬性用戶

要么改變

user: Object; 

通過

user: any;

在您的profile.component.ts中,這肯定會起作用,因為最初您已將其聲明為對象,因此在運行或構建應用程序打字稿時,編譯失敗,原因是作為user.username進行訪問。 您可以將類型更改為any或創建具有必需屬性的接口或類型,然后將此類型分配給用戶Ex:profile.component.ts:

interface userObject {
  username:string,
  password:string
} 

作為訪問

export class ProfileComponent implements OnInit {
   user : userObject;
}

您已經定義了userProfileComponent類作為Object type.wich沒有Typescript Model defined.Therefore打字稿不知道該結構的User對象。 因此,您可以創建一個這樣的模型。

interface User{
    username : String;
    password: ...
    ....
  }  

然后使用類似user : User類型user : User

該問題將得到解決。

定義對象時,它沒有名字或姓氏。 因此,從ui訪問時會顯示錯誤。 因此,首先按照下面的步驟進行初始化。 然后問題將得到解決。

讓用戶= {firstName:“”,lastName:“”}};

碼:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  let user = {firstName: "", lastName:""};
  constructor(private authService: AuthService, private roter: Router) {}

  ngOnInit() {
    this.authService.getProfile().subscribe(
      profile => {
        this.user = profile.user;
      },
      err => {
        console.log(err);
        return false;
      }
    );
  }
}

Object是指內置對象的構造函數,該函數顯然沒有屬性username 由於您將user類型設置為Object並嘗試訪問不存在的屬性username ,因此顯示錯誤。

如果要定義自己的類型,請參考this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM