【问题标题】:Angular: How to redirect into another page upon submitAngular:如何在提交时重定向到另一个页面
【发布时间】:2019-06-24 08:00:02
【问题描述】:

我开发了这个应用程序 (http://www.anelmad.com),并尝试在提交(Enter 或按钮单击)时将信息显示(单词的字典定义)重定向到另一个页面。

重定向有效,但页面内容不跟随。

在 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>

在这个表格之后,我补充说:

 <router-outlet></router-outlet>

在 home.component.ts 中,我添加了 (this.router.navigate) 和新页面作为参数:

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

在 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'

]

如何将要显示的信息从表单传递到新页面(words.component.html)?

【问题讨论】:

    标签: angular redirect routes components


    【解决方案1】:

    有多种方法可以将数据从一个组件传递到另一个路由组件:

    • 构建服务:从第一个组件开始,将数据设置到服务中。从第二个组件中,从服务中读取数据。由于 Angular 服务是单例的(当服务注册到 root 注入器时),它在所有组件之间共享。

    我有一个有效的 stackblitz 在这里演示:https://stackblitz.com/edit/angular-simpleservice-deborahk

    该示例使用了一个简单的输入元素,但您可以将其扩展为包含所有表单数据。

    • 使用路由参数:如果只需要传递单个或几项,可以使用路由参数。 Angular 提供了必需、可选和查询参数,可用于将路由上的数据从一个组件传递到另一个组件。

    • 新状态属性:使用允许在路由之间传递状态的新 Angular v7.2 功能。有关最后一个选项的更多信息,请参阅此链接:https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多