gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:32:38 26 4
gpt4 key购买 nike

背景

我有一个auth.service.ts,当用户登录时,它会查询数据库并返回我们拥有的有关用户的任何信息。传入数据以创建 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 ) { }

这输出未定义,

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

另外,在模板中,我尝试使用插值 {{auth.user.email}},但这也不起作用。

问题

如何从另一个类访问在 auth.service.ts 中创建的对象 用户。在本例中 profile.component.ts 及其模板 profile.component.html

这是一个继承问题吗?

最小类

    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);
}
}

最佳答案

应该在文件objects.ts中有一个类模型BaseObject,例如

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];
}
}
}
}

您将使用导出类导出此对象。

无论你想在哪里使用这个类

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

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

关于javascript - 在 TypeScript 中访问从另一个类实例化的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com