我正在处理一个Angular项目,其中我加载了一些延迟功能模块,我在其中一个模块中遇到了一个奇怪的错误。
我使用"提供商"在模块级别提供服务。 NgModule的财产。我希望(以前能够以这种方式使用服务)服务将在模块中的所有组件之间共享。但是,当我将服务注入模块中的组件时,它们将作为单独的实例注入。
在我的项目中,我有两个组件,我已经观察过它,列表组件和编辑组件。我在我的服务中设置了一个值,而我正在尝试与编辑组件共享的列表组件中,但是当我从列表组件路由到编辑组件时,该服务被重新实例化,当我从编辑组件转到列表组件时也一样。
有谁知道可能导致这种情况的原因?我以前能够在模块中使用共享服务,所以我不确定我做错了什么。
以下是组件,模块和服务的代码:
列表组件:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Project } from '../../../shared/models/project';
import { ProjectService } from '../../project.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-project-list-main',
templateUrl: './project-list-main.component.html',
styleUrls: ['./project-list-main.component.scss']
})
export class ProjectListMainComponent implements OnInit {
private projects$: Observable<Project[]>;
private selectedItem: Project;
onSelectedItem(event){
this.selectedItem = event;
}
editProject(){
this.projectService.setEditProject(this.selectedItem);
this.router.navigateByUrl('/pages/projects/edit');
}
deleteProject(){
this.projectService.delete(this.selectedItem.id);
}
constructor(private router: Router, private projectService: ProjectService) { }
ngOnInit() {
this.projects$ = this.projectService.projects;
}
}
编辑组件:
import { Component, OnInit, Input } from '@angular/core';
import { Validators, FormGroup, FormArray, FormBuilder } from '@angular/forms';
import { ProjectService } from '../../project.service';
import { Project } from '../../../shared/models/project';
import { Router } from '@angular/router';
@Component({
selector: 'app-project-edit-main',
templateUrl: './project-edit-main.component.html',
styleUrls: ['./project-edit-main.component.scss']
})
export class ProjectEditMainComponent implements OnInit {
public projectForm: FormGroup;
@Input() editProject: Project;
constructor(private fb: FormBuilder, private router: Router, private projectService: ProjectService) { }
saveProject(event){
this.projectService.add(event);
this.router.navigateByUrl('/pages/projects');
}
ngOnInit() {
this.projectForm = this.fb.group({
name: ['',Validators.required],
description: [''],
type: ['', Validators.required]
});
this.projectService.editProject.subscribe(editProject => {
if(editProject)
this.projectForm.patchValue(editProject);
});
}
}
服务:
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { Observable } from "rxjs/Observable";
import { Project } from "../shared/models/project";
import { DataService } from "../shared/services/data.service";
import { Router } from "@angular/router";
import { AlertService } from "../shared/alert/alert.service";
@Injectable()
export class ProjectService {
private _projects: BehaviorSubject<Project[]> = new BehaviorSubject([]);
projects: Observable<Project[]> = this._projects.asObservable();
private _editProject: BehaviorSubject<Project> = new BehaviorSubject(null);
editProject: Observable<Project> = this._editProject.asObservable();
editing: boolean = false;
private dataStore: {
projects: Project[]
};
loadall() {
this.dataService.GetAll("projects")
.subscribe(projects => {
this.dataStore.projects = projects;
this._projects.next(Object.assign({}, this.dataStore).projects);
}, error => {
console.log(error);
this.alertService.error('Error', 'Encountered error while loading Projects');
});
}
setEditProject(editProject: Project){
this._editProject.next(editProject);
this.editing = true;
}
add(project: Project) {
this.dataService.Add('projects', project).subscribe(project => {
this.dataStore.projects.push(project);
this._projects.next(Object.assign({}, this.dataStore).projects);
}, error => {
console.log(error);
this.alertService.error('Error', 'Encountered error while adding Project');
});
}
update(project: Project) {
let editId = this._editProject.getValue().id;
project.id = editId;
this.dataService.Update('projects', editId, project).subscribe(() => {
this.dataStore.projects.forEach((p, i) => {
if (p.id === project.id) { this.dataStore.projects[i] = project; }
});
this._projects.next(Object.assign({}, this.dataStore).projects);
}, error => {
console.log(error);
this.alertService.error('Error', 'Encountered error while updating Project');
});
this.editing = false;
this._editProject.next(null);
}
delete(id: number) {
this.dataService.Delete('projects', id).subscribe(response => {
this.dataStore.projects.forEach((p, i) => {
if (p.id === id) { this.dataStore.projects.splice(i, 1); }
});
this._projects.next(Object.assign({}, this.dataStore).projects);
}, error => {
console.log(error);
this.alertService.error('Error', 'Encountered error while deleting Project');
});
}
constructor(private router: Router, private dataService: DataService, private alertService: AlertService) {
this.dataStore = { projects: [] };
this.loadall();
}
}
模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ProjectRoutingModule } from './project-routing.module';
// Primeng module imports
import { CalendarModule, DataTableModule, DialogModule, ConfirmDialogModule, ConfirmationService, PanelModule, DropdownModule } from 'primeng/primeng';
// Dumb components
import { ProjectEditComponent } from './edit/project-edit.component';
import { ProjectListComponent } from './list/project-list.component';
import { ProjectCardComponent } from './card/project-card.component';
import { ProjectDetailComponent } from './detail/project-detail.component';
import { ProjectDeleteOptionsComponent } from './delete/project-delete-options.component';
// Containers
import { ProjectEditMainComponent } from './containers/project-edit-main/project-edit-main.component';
import { ProjectListMainComponent } from './containers/project-list-main/project-list-main.component';
import { ProjectComponent } from './project.component';
// Services
import { ProjectService } from './project.service';
@NgModule({
imports: [
CommonModule,
ProjectRoutingModule,
FormsModule,
ReactiveFormsModule,
DataTableModule,
DropdownModule,
PanelModule
],
declarations: [
ProjectCardComponent,
ProjectDetailComponent,
ProjectEditComponent,
ProjectListComponent,
ProjectDeleteOptionsComponent,
ProjectComponent,
ProjectEditMainComponent,
ProjectListMainComponent
],
providers: [ProjectService]
})
export class ProjectModule { }
答案 0 :(得分:0)
如果您需要以下内容,则只需导入另一个模块(A):
知道这一点,如果你导入了一个也提供服务的模块(A),并且最终得到了该服务的新实例,那么该模块(A)可能被错误地设置了,因为你期望这个服务成为一个应用程序范围的单身人士。
标准模块注册可用于底层组件的服务。共享模块,如果它还希望共享服务,则在应用程序的根目录上注册服务,这可以使用 .forRoot()方法来完成。
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { authObjService } from './service/authObj';
import { loginGuard } from './service/loginGuard';
import {loginButton} from './directive/login-button/login-button'
import {logoutButton} from './directive/logout-button/logout-button'
@NgModule({
declarations: [loginButton, logoutButton],
imports: [CommonModule],
exports: [loginButton, logoutButton],
})
export class authenticationModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: authenticationModule,
providers: [authObjService, loginGuard]
}
}
}