【问题标题】:TypeError: Cannot read property 'UserName' of undefined with Angular 2TypeError:无法使用 Angular 2 读取未定义的属性“用户名”
【发布时间】:2017-03-17 14:51:10
【问题描述】:

我想在我的 Angular 2 应用程序中显示当前用户的用户名。后端使用.net core web api开发。

我写了这段代码,但在控制台中得到了这个错误:

TypeError: 无法读取未定义的属性“用户名”

类 AuthService

import {Injectable, EventEmitter} from "@angular/core";
import {Http, Headers, Response, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Injectable()

export class AuthService {
    authKey = "auth";

    constructor(private http: AuthHttp) {
    }

    // Persist auth into localStorage or removes it if a NULL argument is given
    setAuth(auth: any): boolean {
        if (auth) {
            localStorage.setItem(this.authKey, JSON.stringify(auth));
        }
        else {
            localStorage.removeItem(this.authKey);
        }
        return true;
    }

    // Retrieves the auth JSON object (or NULL if none)
    getAuth(): any {
        var i = localStorage.getItem(this.authKey);
        if (i) {
            return JSON.parse(i);
        }
        else {
            return null;
        }
    }

    // Returns TRUE if the user is logged in, FALSE otherwise.

    isLoggedIn(): boolean {
        return localStorage.getItem(this.authKey) != null;
    }

    **get() {
        return this.http.get("api/Accounts")
            .map(response => <User>response.json());
    }**

}

我确定用户已登录,因为我可以读取他的令牌。

Web api 方法

 /// <summary>
        /// GET: api/accounts
        /// </summary>
        /// <returns>A Json-serialized object representing the current account.</returns>
        [HttpGet()]
        public IActionResult Get()
        {
            var id = GetCurrentUserId(); 
            //var id = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var user = DbContext.Users.Where(i => i.Id == id).FirstOrDefault();
            if (user != null) return new JsonResult(new UserViewModel()
            {
                Type = user.Type,
                UserName = user.UserName,
                Email = user.Email,
                DisplayName = user.DisplayName,
                PhoneNumber = user.PhoneNumber,
                DisplayPhoneNumber = user.DisplayPhoneNumber,
                Description = user.Description

            }, DefaultJsonSettings);
            else return NotFound(new { error = String.Format("User ID {0} has not been found", id) });
        }

打字稿中的类用户

export class User {
    constructor(
        public Type: number,
        public UserName: string,
        public DisplayName: string,
        public PhoneNumber: string,
        public DisplayPhoneNumber: boolean,
        public Description: string,
        public Password: string,
        public PasswordNew: string,
        public Email: string
    ) {
    }
}

angular 2中的组件代码

import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {AuthService} from "./auth.service";
import {AuthHttp} from "./auth.http";
import {User} from "./user";

@Component({
    selector: "home",
    templateUrl: "templates/home.component.html",
    //template: `<h1>Home Component</h1>`
})

export class HomeComponent {

    isRegister: boolean;
    currentUser: User;
    constructor(
        public router: Router,
        public authService: AuthService,
        private activatedRoute: ActivatedRoute
    ) {

        //this.isRegister = this.authService.isLoggedIn();
        //console.log(this.isRegister);
    }
    ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => this.currentUser = User
            );           
            console.log(this.isRegister);
            console.log(this.currentUser.UserName);               
        }
    }
}

代码模板 html

 <div *ngIf="currentUser"><h1>{{currentUser.UserName}}</h1></div>

我不明白为什么这不起作用。

【问题讨论】:

  • console.log(this.currentUser.UserName);该行是否正确记录了用户名?
  • 此时console.log(this.currentUser.UserName);控制台写未定义
  • 用户名是否在您的模板中正确显示?如果是,那么 Bougarfaoui El houcine 做对了

标签: angular .net-core webapi2


【解决方案1】:

您正试图在this.authService.get() 解析User 值之前访问this.currentUser.UserName,因为this.authService.get 是异步的,所以这样做:

     ngOnInit() {
        if (this.authService.isLoggedIn()) {
            this.authService.get().subscribe(
                User => {
                  this.currentUser = User
                  console.log(this.isRegister);
                  console.log(this.currentUser.UserName);
            });           

        }
    }

【讨论】:

  • ´

    {{currentUser?.UserName}}

    ´ 我试试这个,但没用
  • 我不这么认为,第一次this.currentUser是未定义的,当你试图访问undefined的属性时会抛出错误。
  • @Cicciux 你试过我的解决方案了吗?
  • 是的,我尝试过并且工作正常.. 但问题出在 console.log 中,因为我将其称为 authService.get() ???
  • yes exaclty console.log 将在 authService.get() 解析 User 之前执行,因为它是异步的。
【解决方案2】:

尝试替换:

currentUser: User;

作为

currentUser = new User();

控制台中未定义的错误消失了。

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2018-09-26
    • 2019-07-27
    • 2016-05-08
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多