2017-09-12 6 views
0

非常に悪いと私の英語のために申し訳ありません、私はロシアから来ました。私はあなたに尋ねたいと思う。私を助けてください。 私は4番のサービスを持っていますが、どのように多くのコンポーネントでそれを管理できますか?さまざまなコンポーネントでデータサービスを取得するにはどうすればよいですか?

は、これは私のサービスです:

import {EventEmitter, Injectable} from '@angular/core'; 

@Injectable() 
export class AuthService { 
    status: boolean = false; 
    userAuth: EventEmitter<boolean> = new EventEmitter(); 
    auth() { 
     this.status = true; 
     this.userAuth.emit(this.getAuth()); 
    } 
    logout() { 
     this.status = false; 
     this.userAuth.emit(this.getAuth()) 
    } 
    getAuth() { 
     return this.status; 
    } 
} 

これが私の最初のコンポーネントです。私はすでにngOnInitでサービスに登録しています

import {Component, OnInit} from '@angular/core'; 
import {ApiService} from "../../service/api/api.service"; 
import {BlockUI, NgBlockUI} from 'ng-block-ui' 
import {AuthService} from "../../service/auth/auth.service"; 

@Component({ 
    selector: 'app-header', 
    templateUrl: './header.component.html', 
    styleUrls: ['./header.component.less'], 
    providers: [ApiService, AuthService] 
}) 
export class HeaderComponent implements OnInit { 
    isLogin: boolean = false; 
    @BlockUI() blockUI: NgBlockUI; 
    constructor(private as: ApiService, public authService: AuthService) { 
     this.blockUI.start(); 
     this.as.isLogin().then((res) => { 
     if (res.hasError()) return false; 
     if (res.getResponse().login) this.authService.auth(); 
     if (!res.getResponse().login) this.authService.logout(); 
     // this.isLogin = this.authService.getAuth(); 
     this.blockUI.stop(); 
     }); 
    } 
    ngOnInit() { 
     this.authService.userAuth.subscribe((status) => { 
     this.isLogin = status; 
     console.log('status', status); 
     console.log('this.isLogin', this.isLogin); 
     }) 
    } 
    logout() { 
     this.as.logout().then((res) => { 
     if (res.hasError()) return false; 
     this.authService.logout(); 
     // this.isLogin = this.authService.getAuth(); 
     }); 
    } 
} 

しかし、別のコンポーネントでサービスを呼び出すと、新しいサービスが呼び出されます。

あなたがサービスのデータを共有することはできませんが、あなたの特定のコンポーネントのみに特異的で、コンポーネントレベルでサービスを提供する場合、インスタンスをサービスし、角度がサービスのシングルトンオブジェクトを作成すると、あなたのメインモジュールにそれを追加する必要があり
import {Component, EventEmitter, OnInit, Output} from '@angular/core'; 
import {FormBuilder, FormGroup, Validators} from "@angular/forms" 
import {ApiService} from "../../service/api/api.service"; 
import {AuthService} from "../../service/auth/auth.service"; 

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.less'], 
    providers: [ApiService, AuthService] 
}) 
export class LoginComponent { 
    formLogin: FormGroup; 

    constructor(private fb: FormBuilder, private as: ApiService, public authService: AuthService) { 
    this.formLogin = fb.group({ 
     email: [null, Validators.compose([Validators.required, Validators.pattern(/^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)])], 
     password: [null, Validators.compose([Validators.required, Validators.minLength(6)])] 
    }); 
    } 

    auth(form) { 
    this.as.authUser(form).then(res => { 
     if (res.hasError()) return false; 
     this.formLogin.reset(); 
     this.authService.auth(); 
    }); 
    } 
} 
+0

にNgModuleのプロバイダの配列ではなく、コンポーネントにあなたのサービスを追加します。 – n00dl3

+0

はい、それは私を助けました。ありがとうございました:) –

+0

この回答を見る-https://stackoverflow.com/questions/46044729/angular2-sharing-variable-or-global-variable-between-pages-components/46045167#46045167 –

答えて

1

にサービスを注入。

Angular2依存性注入(DI)は、次のように多かれ少なかれに動作します:

  • あなたはあなたにそれがでチェックし、何かのインスタンスを提供するために、DIを要求したとき、すべてのコンポーネントがそのインジェクタとそのプロバイダ
  • を持っていますプロバイダが "レシピ"を見つけたらインスタンスを作成し、インジェクタに入れて、プロバイダの "レシピ"とインジェクタのインスタンスが見つからない場合は、
  • を提供します同じ要求が父親に持ち上げられ、その要求がプロバイダに「レシピ」または注射されているかどうかがチェックされますこの階層チェーン(メインモジュールまで)で、要求されたトークンのプロバイダが見つかると、その時点からインスタンスが作成され、要求されたとおりに返されます。
  • リクエストインスタンスを持つインジェクタを持つコンポーネントの子は、そのインスタンスをシングルトンとして受け取ります。

したがって、特定の問題に戻ると、どちらのコンポーネントにも「レシピ」が含まれているため、AuthServiceの2つの相違点があります。そのため、両方ともインスタンスを作成してインジェクタに保存し、 DIによって要求される。することができますあなたの問題を解決するために

  • 各コンポーネントのデコレータから削除はのAuthService
  • のプロバイダは、モジュールのデコレータのメタデータ内のプロバイダにのAuthServiceを追加メタデータ。
  • @Component({ 
        selector: 'app-login', 
        templateUrl: './login.component.html', 
        styleUrls: ['./login.component.less'], 
        providers: [ApiService] 
    }) 
    export class LoginComponent { /* ... */ } 
    

    __

    @Component({ 
        selector: 'app-header', 
        templateUrl: './header.component.html', 
        styleUrls: ['./header.component.less'], 
        providers: [ApiService] 
    }) 
    export class HeaderComponent implements OnInit { /* ... */ } 
    

    __

そして、メインモジュールの宣言

@NgModule({ 
    imports: [ /* ... */ ], 
    declarations: [ /* ... */ ], 
    providers: [AuthService, OtherServices], 
}) 
0

コンポーネント間でしたがって、コンポーネント間で共有するためにメインモジュールで提供する必要があります。 @Componentから

削除サービスプロバイダーとあなたは両方のコンポーネントプロバイダでのAuthServiceクラスを提供するので、その後ちょうどあなたがのAuthServiceの新しいインスタンスを受信して​​いるコンポーネントごとにcomponent'sconstructor

providers: [AuthService], 

Your ng module should be like: 

@NgModule({ 
     declarations: [ 
     AppComponent, 
     LoginComponent, 
     HeaderComponent, 
    ], 
     imports: [ 
     BrowserModule, 
     RoutingModule 
     ], 
     providers: [AuthService], 
     bootstrap: [AppComponent] 
    }) 
    export class AppModule { } 
関連する問題