在两个独立组件之间传递数据

时间:2017-05-16 17:03:02

标签: angular angular-cli

我想在两个独立组件之间传递数据。

例如:

  1. 我有第一个包含输入文本和提交按钮的组件。带输入框的第二个组件
  2. 当用户在第一个组件的文本框中输入数据并单击提交时,他将被路由到第二个组件,其中在第一个组件的输入文本框中输入的数据应该位于第二个组件的文本框内。
  3. 我尝试使用@Input和@Output,但这是针对父子层次结构。
  4. 在我的情况下,我有2个独立的组件,其中用户路由从一个页面到另一个页面是整个视图更改
  5. 我听说过使用服务但无法在线找到合适的示例或文档。

1 个答案:

答案 0 :(得分:0)

您可以提供常用服务,我将其命名为商店。例如,您可以创建表单存储forms.store.ts。这个商店将是一个服务

@Injectable()
export class FormsStore {
  inputText : string = '';
  constructor(){
       //Code here
  }
  //Other Functions 
}

在form.component.ts中:

 @Component({
    selector: 'form',
    encapsulation: ViewEncapsulation.None,
    template: require('./form.component.html')
})

export class FormComponent{

  constructor(private store: FormsStore) {
  }

  onFormSubmit(value){
   this.store.inputText = value;
  }

}

在form.component.html中:

<input (keydown.enter)="onFormSubmit(input.value)" #input>

现在在其他组件中,您可以再次创建商店的实例并引用&quot; inputText&#39;值为store.inputText并使用它。

相关问题