我一直在试图在我的两个组件之间共享一些数据。该组件通过routerOutlet在我的主要成分,它看起来像这样既显示:使用服务在组件之间共享数据
import { Component } from '@angular/core';
import { AccountService } from './account.service';
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [AccountService]
})
export class AppComponent {
constructor(public accountService:AccountService){
}
}
我在那里,我想在我的服务设置值登录组件,如:
import { Component } from '@angular/core';
import { AccountService } from './account.service';
@Component({
moduleId: module.id,
selector: 'login-component',
templateUrl: 'login.component.html',
})
export class LoginComponent {
constructor(public accountService:AccountService){
}
setAccount(userName: string, password: string){
this.accountService.setAccount(userName,password);
}
}
setAccount方法从我的模板中调用。现在,在另一个组件中,我试图从服务中获取帐户并显示用户名,但这不起作用。另一个组成部分是这样的:
import { Component } from '@angular/core';
import { AccountService } from './account.service';
@Component({
moduleId: module.id,
selector: 'home-component',
templateUrl: 'home.component.html',
})
export class HomeComponent {
constructor(public accountService:AccountService){
}
}
我的模板显示的用户名是这样的:
{{accountService.getAccount().name}}
最后,这里是我的服务:
import { Injectable } from '@angular/core';
export class Account{
name: string;
password: string;
}
@Injectable()
export class AccountService {
private account = {name: "", password: ""};
getAccount(){
return this.account;
}
setAccount(username: string, password: string){
this.account.name = username;
this.account.password = password;
}
}
我在做什么错误?
编辑:看来问题是,当第二个组件显示,重新加载页面,导致该服务重新启动?这里是我的登录组件的HTML,因为我怀疑问题可能是在这里:
<div class="topbar">
<a title="Made for the University of Southern Denmark." href="login.html">
<img src="img/sdulogo.png">
</a>
</div>
<div class="logincontainer">
<img src="img/profilepic.png">
<form action="/home">
<div class="form-input">
<input #username type="text" id="username"
placeholder="Enter Username" required>
</div>
<div class="form-input">
<input #password type="password" id="password"
placeholder="Enter Password" required>
</div>
<button (click)="setAccount(username.value, password.value)" type="submit" class="btn-login">LOGIN</button><br>
<a href="http://www.google.dk">Create Account</a><br>
<a href="#">Forgot Password?</a>
<p>{{accountService.getAccount().name}}</p>
</form>
</div>
您是否在控制台中看到任何错误消息?如果是这样,请将它们添加到您的问题。 –
没有任何错误信息。 – Jesper
作为应用程序的用户,您要从登录页面转到主页面的操作顺序是什么?我的猜测是你重新加载页面。 –