0

喝水.component.ts

    import { Component } from 'angular/core';
    import { userInfoService } from 'some/path';

    @Component({
    selector: 'drink-water';
    templateUrl: './drink-water.component.html'
    })

    export class DrinkWaterComponent implements OnInIt {
    ...
    ...
    userInfo: userInfoModel;

    constructor (public userInfoService : UserInfoService) {}

    ngOnInit() {

    this.readUsrInfo();

    }

    readUsrInfo() {
    console.log('user info is', this.userInfoService)

   //need gender here ..to do some logic
   //need gender here..

        }

用户信息.service.ts

import { Injectable } from '@angular/core';
import { UserInfoModel } from 'some/path';

@Injectable({
providedIn: 'root'
})

export class UserInfoService {
public userInfo: UserInfoModel;

constructor() {}
}

用户信息.model.ts

export class UserInfoModel {
gender: string;
userName: string;
hasKids: boolean;
constructor(data: UserInfoModel) {
this.userName = date.userName;
this.gender = data.gender;
}
}

饮用水组件的控制台输出 -> readUsrInfo(console.log()) 请将 > 替换为向下实心箭头作为 json 结构。我无法格式化

   > userInfoService {}
    > userInfo : UserInfoModel
      userName: peggy
      gender: female
      hasKids: true
      student: false
      >foods: {vegetables: Array(3), Fruits: Array(5)}
    >_proto_: Object

问题

如果我尝试从控制器控制 this.userInfoService,我会得到上面的控制台输出。如何在 readUsrInfo 方法中访问姓名和性别?this.userInfoService.gender 返回未定义。

任何帮助表示赞赏。

4

1 回答 1

0
export class UserInfoModel {
      userName= 'peggy'
      gender = 'female'
      ...
      ...
}

userInfo = new UserInfoModel()

console.log('user gender', userInfo.gender)
于 2019-10-11T20:17:04.713 回答