如何初始化模型并在类中调用自定义函数

时间:2017-10-18 16:05:54

标签: angular

我有一个用户服务,我从我的mongo db中获取一个对象。用户对象包含一个dob,我想将其转换为角度的年龄。

我创建了一个自定义用户类来执行此操作,声明了一个getAge函数。但是,在调用此user.getAge()函数时,它会显示

  

" this.user.getAge()不是函数"

user.model.ts

export class User {

  user: any;

  constructor() {

  }

  getAge() {

return "Age"

  }
}

profile.component.ts

import { UserService } from '../../services/user.service';
import { AuthService } from '../../services/auth.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {User} from '../../models/user.model'

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

    user: User;

    constructor(private authService: AuthService,
        private route: ActivatedRoute,
        private router: Router,
        private userService: UserService) { }

    ngOnInit() {

        this.route.params.switchMap((params) => {
            let user_id = params['id'];
            return this.userService.get(user_id);
        }).subscribe((res) => {
            this.user = res;
            let age = this.user.getAge();
            console.log(age);

        });
    }

}

user.service.ts

import { Injectable } from '@angular/core';
import { ApiService } from './api.service';

@Injectable()
export class UserService {


    path = 'users/';

    constructor(
        private apiService: ApiService
    ) {

    }

    all() {
        return this.apiService.get(this.path);
    }

    create(user) {

        return this.apiService.post(this.path, user);

    }

    get(user_id) {

        let endpoint = this.path + user_id;

        return this.apiService.get(endpoint);
    }

}

user.model.js

let UserSchema = new Schema({

        email: {
            address: {
                type: String,
                lowercase: true,
                //unique: true,

            },
            token: String,
            verified: {
                type: Boolean,
                default: false,
            },
        },
        password: {
            type: String,
        },

        socketId: String,
        isOnline: Boolean,

        phone: {
            countryCode: {
                type: String,
            },
            number: {
                type: String,
            },
            code: String,
            verified: {
                type: Boolean,
                default: false
            },
        },

        jwt: String,

        profile: {
            username: String,
            firstname: String,
            lastname: String,
            dob: String,
            gender: String,
            level: Number,
            location: {
                longitude: String,
                latitude: String
            },
            image: String,
            introduction: String,

            following: [],
            followers: [],

        },

    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
    });

3 个答案:

答案 0 :(得分:2)

UserService.get()返回any因此,typescript允许您将其分配给ProfileComponent.user(类型User)。 new User()永远不会这样称呼 永远退出User的{​​{1}}对象确实会返回UserService.get(),其中包含模型中的所有属性。你需要的是:

Observable<Object>

答案 1 :(得分:0)

    get(user_id) {

       let endpoint = this.path + user_id;

       return this.apiService.get(endpoint).map(res => new User(){//set your user properties here});
   }

答案 2 :(得分:0)

您可以使用对象分配将结果分配给新的用户对象。如下所示

    this.route.params.switchMap((params) => {
        let user_id = params['id'];
        return this.userService.get(user_id);
    }).subscribe((res) => {

        let userRef: User = new User();
        Object.assign(userRef, res);

        this.user = userRef;
        let age = this.user.getAge();
        console.log(age);

    });

或者您可以从user.model.ts

执行此操作
export class User {
user: any;
constructor() {}
  getAge(){ return "Age"}
public static fromObject(obj):User { 
let userRef: User = new User();
Object.assign(userRef, obj);
return userRef;}}

在您的组件或服务中,您可以通过导入用户模型

来完成此操作
this.route.params.switchMap((params) => {
        let user_id = params['id'];
        return this.userService.get(user_id);
    }).subscribe((res) => {

        this.user = User.fromObject(res);
        let age = this.user.getAge();
        console.log(age);

    });