无法读取角度分量中未定义的属性“ 0”

时间:2020-05-01 18:57:34

标签: angular typescript

我有一个用例。 我在angular项目的服务之一中有一个简单的硬编码数组。 服务中的一种方法是返回硬编码数组。

否,我正在尝试使用注入特定服务的组件中的索引来访问数组的元素。 但我收到无法读取未定义的属性“ 0” 如何在component中定义数组?

我的服务看起来像 sample-service.service.ts:

import { Injectable } from '@angular/core';

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

  constructor() { }
  user : any = [
                  {
                    fullName : 'John'
                  },
                  {
                    fullName : 'Peter'
                  }
                ];


  public get currentUserDetails() {
    return this.user;
  }
}

我的组件类如下: sample.component.ts

import { Component, OnInit } from '@angular/core';
import { SampleServiceService } from '../services/sample-service.service';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {

  constructor(private _sampleService : SampleServiceService) { }

  username : string;

  ngOnInit(): void {
      this.username = this._sampleService.currentUserDetails.user[0].fullName;        
  }

}

组件HTML:sample.component.html

    <p>sample works!</p>

<h1>{{username}}</h1>

浏览器控制台如下所示: enter image description here

谢谢!

2 个答案:

答案 0 :(得分:0)

sample.component.ts中访问它的正确语法是:

this.username = this._sampleService.currentUserDetails[0].fullName; 

fullName之前,您没有“用户”属性。

如果要保持调用方式,可以修改getter(currentUserDetails):

get currentUserDetails() {
  return {user: this.user};
}

答案 1 :(得分:0)

以这种方式使用

: