我一直在試圖在我的兩個組件之間共享一些數據。該組件通過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
作爲應用程序的用戶,您要從登錄頁面轉到主頁面的操作順序是什麼?我的猜測是你重新加載頁面。 –