从TypeScript中的另一个类实例化访问对象

时间:2016-11-29 23:42:32

标签: javascript angular typescript

背景

我有一个auth.service.ts当用户登录时会查询database并返回我们对用户的任何信息。传入数据以创建新的object user。它看起来像这样,

 user: User;
 this.user = res;
 console.log(this.user);

输出,

Object account_locked: false affiliate_owner: null business_phone: "8178966767" city_address: null contract: false created_on: null dob: "1984-03-05T06:00:00.000Z" email: "example@email.com" employee_owner: null fax_number: "1234567" first_name: "Nicholas" home_phone: "1234567" id: 7last_name: "theman" middle_name: "dude" mobile_phone: "1234567" ssn: "123456789" state_address: null street_address: null user_auth_level: 1 zip_address: null __proto__: Object

这是真的,这......

console.log(this.user.email);

哪个输出example@email.com

问题

所以当我去另一个班级并像这样添加auth.service.ts时,

import { Auth }                    from './../services/auth.service';

constructor( private router: Router, private auth: Auth, private http: Http  ) { }

输出undefined,

ngOnInit() {
      console.log(this.auth.user);
     }

同样从模板中我尝试使用插值{{auth.user.email}},这也不起作用。

问题

如何从其他班级访问object中创建的user auth.service.ts。在这种情况下profile.component.ts及其模板profile.component.html

这是inheritance的问题吗?

最小班级

    auth.service.ts

    export class Auth {
      lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options, {});
      userProfile: Object;
      logreg: LogReg;
      user: User;
      constructor(private router: Router, private http: Http ) {
            // create users
            this.logreg = new LogReg(profile.email);   
            this.checkRegister(this.logreg).subscribe((res)=>{
                //do something with the response here
                this.user = res;
                console.log(this.user);
            });
    }
}

我想在这里访问该对象用户,

profile.component.ts

import { Auth }                    from './../services/auth.service';

@Component({
    providers: [ Auth ],
    templateUrl: './profile.component.html'
})
export class ProfileComponent implements OnInit {

    constructor( private router: Router, private auth: Auth, private http: Http  ) { }

    ngOnInit() {
      console.log(this.auth.user);
     }
}

1 个答案:

答案 0 :(得分:1)

假设文件BaseObject中有一个类模型objects.ts,如

import * as P from "./protocols"

export class BaseObject implements P.ObjectProtocol {

/** 
     * Fill object by properties dictionary
     * @param properties Object Properties dictionary
    */
    public fill(properties:Object) {
        var self=this;
        for (var i in properties) {
            if (self.hasOwnProperty(i)) {
                self[i]=properties[i];
            }
        }
    } 
}

您将使用export class导出此对象。

你想在哪个地方使用这个课程

import {BaseObject} from "./objects"
export class MyObjectImpl extends BaseObject {
 //...
}

关于共享对象实例的问题,您需要singleton模式,请看这里: Access key data across entire app in Angular 2 & Ionic 2