最近我遇到了这个问题,在这里我似乎找不到找到将实例化对象传递给另一个类的方法。
我需要将实例化的对象userModel从 main.page.ts 传递到 menu.page.ts
我似乎对此知之甚少。我发现一个问题与我的问题非常相似,但是并没有解决问题。
main.page.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { User } from 'src/app/user';
import { EnrollmentService } from '../../../Services/enrollment.service';
import {Md5} from 'ts-md5/dist/md5';
@Component({
selector: 'app-main',
templateUrl: './main.page.html',
styleUrls: ['./main.page.scss'],
})
export class MainPage implements OnInit {
SERVER_URL = 'http://ruben-pc/form/76/2';
submitted = false;
userModel = new User('CT', 'testeteste', false);
md5 = new Md5();
constructor(public httpClient: HttpClient, private enrollmentService: EnrollmentService) {
}
ngOnInit() {
}
}
menu.page.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../../user';
@Component({
selector: 'app-menu',
templateUrl: './menu.page.html',
styleUrls: ['./menu.page.scss'],
})
export class MenuPage {
pages = [
{
title: 'Login',
url: '/menu/main',
icon: 'home'
},
{
title: 'Funcionalidades',
children: [
{
title: 'Listagem Questionário',
url: '/menu/flutter',
icon: 'ios-clipboard'
},
]
}
];
constructor() {
console.log(this.userModel.loggedIn);
}
}
答案 0 :(得分:0)
似乎您有两个位于不同路径上的组件,您可能应该使用依赖注入来创建此userModel
,例如:
@NgModule({
...
providers: {
...
{
provide: User, // needs to be decorated with @Injectable
useValue: User('CT', 'testeteste', false),
}
}
})
class SomeModule {}
以及您的组件中
constructor(
...
user: User, // then it will be available under this.user
)
还有很多文档,只需阅读Angular documentation