2017-02-17 80 views
2

我已經在stackoverflow中搜索了很多,但我沒有找到一個真正的解釋我的問題.... 我試圖做一個簡單的angular2應用程序,與RouterModule ,一個簡單的服務和一個簡單的組件。 所以:
我的路由器模塊:Angular 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>,這會觸發console.log我已寫入組件和ser副構造...,我每次瀏覽時都會在控制檯中看到'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!