我正在尝试使用公共共享服务在组件之间共享数据。这就是服务。
@Injectable()
export class JobService {
public jobType=null;
public examples=[];
}这是我的第一个组件。组件中的完整代码太长了,所以我只是添加了一个...来表示其余的代码,但是在这个组件中设置了服务的jobType和examples变量。
@Component({
selector: 'app-job',
templateUrl: './job.component.html'
})
export class JobComponent implements OnInit {
constructor(private jobService: JobService, private authService: AuthService, private router: Router) {
}
...
}第二个组件是
@Component({
selector: 'app-preview',
template:'./preview.component.html'
})
export class PreviewComponent implements OnInit {
jobType;
examples;
constructor(private jobService: JobService) {
}
ngOnInit() {
this.jobType=this.jobService.jobType;
this.examples=this.jobService.examples;
}
}因此,我们的想法是,它应该能够获得在JobComponent内的服务中设置的jobType和examples变量。
服务本身在模块文件中提供
@NgModule({
declarations: [
JobComponent,
JobListComponent,
JobDetailsComponent,
PreviewComponent
],
imports: [
CommonModule,
FormsModule,
RouterModule,
TabsModule
],
providers: [JobService]
})
export class JobModule {
}我的理解是,这意味着JobService只实例化一次,并且在组件之间共享。
这个问题出现在JobComponent的html模板中。它包含一个路由器链接,用于在新选项卡中打开PreviewComponent。
<a target="_blank" routerLink="/preview">Preview</a>当这个链接打开时,已经在JobComponent中设置了JobService中的变量(我检查了这是真的)。/preview路由与PreviewComponent相关联。当新窗口打开并且PreviewComponents读取JobService变量时,它们还没有被设置,这让我相信PreviewComponent已经创建了一个全新的JobService实例。然而,根据Angular2 - Share data between components using services的说法,如果JobService只在模块文件中提供一次,则不应该发生这种情况。谁能告诉我为什么JobService似乎不能在这两个组件之间共享?
发布于 2018-01-28 04:11:23
这是因为您要在新窗口中打开页面。未保留JobService的状态。一种可能的解决方案可能是使用url查询参数将JobService的状态传递给预览组件,并在新页面中重新构建服务,例如,导航到/preview?jobType=something&examples=are,comma,separated,list或在浏览器中保存状态(本地存储、cookie等)并在页面初始化时读取它。
发布于 2018-01-28 04:24:15
若要保存共享资源的状态,应使用BehaviorSubject%s。
@Injectable()
export class JobService {
public jobType$: BehaviorSubject<any> = new BehaviorSubject('');
public examples$: Behavior Subject<any[]> = new BehaviorSubject([]);
public jobTypes = null;
public examples = [];
setJobType(jobType) {
this.jobTypes = jobType;
this.jobType$.next(this.jobTypes);
}
//set the same way for examples
}然后在你的每个组件中。
@Component({
selector: 'app-job',
templateUrl: './job.component.html'
})
export class JobComponent implements OnInit {
constructor(private jobService: JobService, private authService: AuthService, private router: Router) {}
//somewhere like ngOnInit subscribe to jobType$ and or examples$
//on some event or trigger of the ui call the setJobType method with changes.
}
@Component({
selector: 'app-preview',
template:'./preview.component.html'
})
export class PreviewComponent implements OnInit {
jobType;
examples;
constructor(private jobService: JobService) {
}
ngOnInit() {
this.jobService.jobType$.subscribe(result => this.jobType = result);
this.jobService.examples$.subscribe(result => this.examples = result);
}
}https://stackoverflow.com/questions/48479998
复制相似问题