2017-02-17 9 views
2

私はstackoverflowで多くの検索をしましたが、私の問題には本当の説明はありません.... RouterModuleを使って簡単なangular2アプリケーションを作成しようとしています、シンプルなサービスとシンプルなコンポーネントです。 ので:
私のルータモジュール:角2のナビゲーションはすべてのサービスとコンポーネントを初期化します

import { NgModule } from '@angular/core'; 
import { RouterModule, Routes } from '@angular/router'; 

import { StudentListComponent } from '../students-list.component'; 
import { StudentComponent } from '../student.component'; 

const routes: Routes = [ 
    { path: 'students', component : StudentListComponent }, 
    { path: 'student/:id', component: StudentComponent }, 
    { path: '**', redirectTo : '/students', pathMatch: 'full' }, 
    { path: '', redirectTo : '/students', pathMatch: 'full' } 
]; 

@NgModule({ 
    imports: [ RouterModule.forRoot(routes) ], 
    exports: [ RouterModule ] 
}) 

export class AppRouterModule { } 

マイコンポーネント:

import { Component, OnInit } from '@angular/core'; 
import { StudentService } from './services/student.service'; 
import { Student } from './class/Student'; 

@Component({ 
    selector: 'student-list', 
    templateUrl: 'app/views/students-list.component.html', 
    styleUrls: ['app/views/styles/students-list.component.css'], 
    providers : [ StudentService ] 
}) 

export class StudentListComponent implements OnInit { 

    private studentService: StudentService; 
    students: Student[]; 

    constructor(studentService: StudentService) { console.log('reinit component'); 
    this.studentService = studentService; 
    } 

    ngOnInit(): void { 
    if(!this.students) 
     this.studentService.getStudents().then((students) => this.students = students); 
    } 

} 

マイサービス:

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/toPromise'; 
import { Student } from '../class/Student'; 
import { Note } from '../class/Note'; 
import { CourseService } from './course.service'; 

@Injectable() 
export class StudentService { 

    static service: StudentService; 

    private httpUrl = "http://localhost/NotesApp/webServ/"; 
    private students: Student[]; 
    private courseService: CourseService; 
    private http:Http; 

    constructor(courseService: CourseService, http:Http){ console.log('reinit service'); 
    this.courseService = courseService; 
    this.http = http; 
    } 

    getStudents(): Promise<Student[]> { 
     return this .http 
        .get(this.httpUrl+'getStudents') 
        .toPromise() 
        .then(response => this.hydratedStudentArray(response.json())) 
        .catch(this.handleError); 
    } 

    getStudentById(id: number): Promise<Student> { 
     return this .http 
        .get(this.httpUrl+'getStudent/'+id) 
        .toPromise() 
        .then(response => this.hydratedStudent(response.json()[0])) 
        .catch(this.handleError); 
    } 

    private hydratedStudentArray(jsonArray: { id: number, firstname: string, lastname: string }[]): Student[]{ 
    let hydratedArray: Student[] = []; 

    for (let jsonElement of jsonArray){ 
     hydratedArray.push(new Student(jsonElement.id, jsonElement.lastname, jsonElement.firstname)); 
    } 

    return hydratedArray; 

    } 

    private hydratedStudent(jsonElement: { id: number, firstname: string, lastname: string }): Student{ 
    return new Student(jsonElement.id, jsonElement.lastname, jsonElement.firstname); 
    } 

    private handleError(error: any): Promise<any> { 
    console.error('An error occurred', error); // for demo purposes only 
    return Promise.reject(error.message || error); 
    } 

} 

だから私の問題がある:私は <a routerLink="/students">Students</a>のようなリンクを使用して移動するとまたは<a [routerLink]="['/student', student.id]" >{{ student.lastname }} {{ student.firstname }}</a>、これはコンポーネントとserで書かれたconsole.logをトリガーします私がナビゲートするたびに私のコンソールに 'reinit component'と 'reinit service'が表示されます...どうすればこの問題を回避できますか? ありがとう

+1

http://stackoverflow.com/questions/33940095/angular2-routing-keeping-state-of-component-when-route-changes/36010817#36010817に記載されているようなカスタム再利用戦略を実装できます。通常、より良いアプローチは、コンポーネントを特定の方法でビルドすることです。ナビゲートするときに破棄されたときや、ナビゲートするときに再作成されるときは問題になりません。たとえば、コンポーネントの代わりに共有サービスにステータスを格納することができます。 –

+0

私は私のサービスの私有財産に学生を預けたいと思っていましたが、これは最後に再初期化されました。もしそれがシングルトンでないのなら...そうです、あなたはこれが角の本当の機能だと言っていますか? ... –

+0

サービスをコンポーネントに提供すると、サービスはコンポーネントとともに作成され、破棄されます。あなたのユースケースでは、それは親コンポーネントで提供されるべきです(そして、コンポーネントが追加される ''を含むもの、または '@NgModule()'で提供されるものでなければなりません)。アプリケーション全体で作成し、アプリケーションで破棄します。 –

答えて

2

問題はここにあります:コンポーネント自体にプロバイダをロードしましたが、モジュール全体が使用できるように、自分のNgModuleで宣言する必要があります。 ...

providers: [ StudentService ] 

およびサービスは、私はコンポーネントと呼ばれるたびに再instanciedた理由です ありがとう:私はこのようなコンポーネントで再宣言プロバイダでした!

関連する問題