簡體   English   中英

使用服務在組件之間共享數據

[英]Using service to share data between components

我一直在嘗試在兩個組件之間共享一些數據。 這兩個組件都通過我的主要組件中的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>

您可以使用BehaviorSubject

您的服務應如下所示:

import { BehaviorSubject } from 'rxjs/Rx';
import { Injectable } from '@angular/core';

export class Account{
    name: string;
    password: string;
}

@Injectable()
    export class AccountService  {  

    private account: BehaviorSubject<Account>; 

   constructor() {
       this.account = <BehaviorSubject<Account>>new BehaviorSubject({});
   }
   getAccount(){
       return this.account.asObservable();
   }

   setAccount(username: string, password: string){
       this.account.next({name: username, password: password})
   }
}

然后在您的login.component.ts中:

constructor(private accountService:AccountService){}

setAccount(userName: string, password: string){
    this.accountService.setAccount(userName,password); 
} 

ngOnInit(): void {
   // example of usage
    this.setAccount('admin', 'admin')
}

在您的home.component.ts中:

private account:Account;
constructor(private accountService:AccountService){}

getAccount() {
    this.accountService.getAccount().subscribe(account => this.account = account)
}

ngOnInit(): void {
    // example of usage
    this.getAccount()
}

在您的主模板中像這樣{{account.name}}使用它

希望這可以幫助!

您可以嘗試將其添加為NgModule中的提供程序,而不是將AccountService添加為app.component中的提供程序嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM