【发布时间】:2019-08-01 07:18:40
【问题描述】:
我正在编写一个 Angular 2 应用程序,其中包含表示页面的组件。当我导航到一个新的组件/页面时,我还想跟踪我以前在哪个组件/页面上。我正在通过一项服务来实现这一目标。
当我在组件构造函数中订阅服务时,看起来我的数据已正确保存到属性中。但是,如果我稍后尝试访问此属性,它会说它是未定义的。这是为什么呢?
按比例缩小的示例:我的两页是第一页和第二页。第一页有一个转到第二页的按钮; page-two 有一个 source-page 属性,它应该存储“page-one”作为值。
源代码:history.service.ts
import { Injectable, EventEmitter } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class HistoryService {
priorPage = new EventEmitter<string>();
constructor() { }
}
源代码:page-one.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HistoryService } from '../services/history/history.service';
@Component({
selector: 'app-page-one',
templateUrl: './page-one.component.html',
styleUrls: ['./page-one.component.css']
})
export class PageOneComponent implements OnInit {
constructor(private router: Router, private route: ActivatedRoute, private historyService: HistoryService) {
}
ngOnInit() {
}
loadPageTwo() {
this.historyService.priorPage.emit("page-one");
this.router.navigate(['/pagetwo']);
}
}
源代码:page-one.component.html
<p>
Welcome to Page1!
</p>
<button (click)="loadPageTwo()">Go To Page Two</button>
源代码:page-two.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HistoryService } from '../services/history/history.service';
@Component({
selector: 'app-page-two',
templateUrl: './page-two.component.html',
styleUrls: ['./page-two.component.css']
})
export class PageTwoComponent implements OnInit {
sourcePage: string;
constructor(private router: Router, private route: ActivatedRoute, private historyService: HistoryService) {
this.historyService.priorPage.subscribe(
(priorPage: string) => {
this.sourcePage = priorPage;
console.log('priorPage = ' + priorPage);
console.log('sourcePage = ' + this.sourcePage);
}
);
}
ngOnInit() {
}
loadPageOne() {
this.router.navigate(['/pageone']);
}
logSource() {
console.log('logSource: sourcePage = ' + this.sourcePage);
}
}
源代码:page-two.component.html
<p>
Welcome to Page2!
</p>
<p>You came from {{source}}</p>
<button (click)="loadPageOne()">Go To Page One</button>
<button (click)="logSource()">Log Source</button>
当我从第一页导航到第二页然后点击“日志源”按钮时的输出是:
priorPage = page-one
sourcePage = page-one
logSource: sourcePage = undefined
如何更新它以使 sourcePage 属性保留该值?
【问题讨论】:
-
从您共享的代码中看起来不像,但只是确保您没有使用
ChangeDetection.OnPush是吗?