简体   繁体   English

使用Angular在路线之间传递数据

[英]Passing data between routes with Angular

Suppose I am currently on the page 'A' with a inputfield. 假设我当前在带有输入字段的页面“ A”上。 I enter "123" in the inputfield and navigate to page 'B'. 我在输入字段中输入“ 123”,然后导航到页面“ B”。 (I don't need the value '123' on Page B). (我不需要B页上的值“ 123”)。 But when I navigate from 'B' back to page 'A' I want the previusly entered value '123' is still in the inputfield. 但是,当我从“ B”导航回到页面“ A”时,我希望先前输入的值“ 123”仍在输入字段中。 Is there a build in options in Anuglar to do this without passing the value through the route:id like 'pageb/123' and without storing it in the localstorage? Anuglar中是否有内置选项来执行此操作,而无需将值传递给'pageb / 123'之类的route:id且不将其存储在localstorage中?

You can use services, for store some variable 您可以使用服务,用于存储一些变量

import { Injectable } from '@angular/core';

@Injectable()
export class MyService{
    public myVar = '';

    constructor(){}
}

then add this service in provider of app.module.ts 然后将此服务添加到app.module.ts的 提供者

Now you can use this service in your components. 现在,您可以在组件中使用此服务。

import { MyService } from '...';

export class AComponent implements OnInit {

    constructor(private myService: MyService){}
    ngOnInit(){
        this.myService.myVar = 'something';
    }
}

You could store it in a service. 您可以将其存储在服务中。 There is no other way because when you navigate away your component instance is destroyed. 没有其他方法,因为当您离开时,您的组件实例将被销毁。 If you navigate back a new instance of that component is created. 如果向后导航,则会创建该组件的新实例。

您可以使用具有大量此类情况的ngrx / store,以下是链接https://github.com/ngrx/platform/blob/master/docs/store/README.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM