Angular: How to redirect into another page upon submit

时间秒杀一切 提交于 2019-12-13 04:12:51

问题


I developed this app (http://www.anelmad.com) and I am trying to redirect the display of information (dictionary definitions of words) upon submit (Enter or button click) into another page.

The redirection works but the content of the page does not follow.

in home.component.html:

<form #myForm>
     (...)

    <input type="text" class="form-control" #elem 
    (keyup)="onNameKeyUp(elem.value)"
    [ngModelOptions]="{standalone: true}"
    [(ngModel)]="latinButton"
    (focus)="onNameKeyUp(elem.value)"
    placeholder="Enter"/>

    <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="submit" 
    (click)="getWordList()">
            <i class="fa fa-search"></i>
        </button>
      </span>

After this form, I added:

 <router-outlet></router-outlet>

Inside home.component.ts, I added (this.router.navigate) with the new page as an argument:

  getWordList(){
  this.router.navigate(['/words']);
  this.webservice.getWords(this.spelling, this.selected)
  .subscribe((res: Array<Word>)=> {
  (...)

in app.module:

const myRoutes: Routes=[
  {path: 'words', component: WordsComponent},
  {path: 'about', component: AboutComponent},
  {path: 'home', component: HomeComponent},
  {path: '', redirectTo: '/home', pathMatch:'full'},
  {path: '**', redirectTo: '/home', pathMatch:'full'

]

How do I pass the information to be displayed from the form into the new page (words.component.html)?


回答1:


There are numerous ways to pass data from one component to another routed component:

  • Build a service: From the first component, set the data into the service. From the second component, read the data from the service. Since an Angular service is a singleton (when the service is registered with the root injector), it is shared between all of the components.

I have a working stackblitz demonstrating this here: https://stackblitz.com/edit/angular-simpleservice-deborahk

The example uses a simple input element, but you could expand it to include all of the form data.

  • Use route parameters: If you just need to pass a single item or a few items, you can use route parameters. Angular provides required, optional, and query parameters that can be used to pass data on the route from one component to another.

  • New State property: Use the new Angular v7.2 feature that allows passing state between routes. See this link for more information about this last option: https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb



来源:https://stackoverflow.com/questions/54450744/angular-how-to-redirect-into-another-page-upon-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!