在React Router中传递动态对象

时间:2019-02-14 23:52:09

标签: angular router

你好,如何在angular7.2.4中传递动态数据?我过去2个小时一直在搜寻Google,但看不到简单的答案。在SO和github上,他们说要创建共享服务,请在data上使用Routes对象,看来angular在react中没有这样的功能

<Route
  path='/dashboard'
  render={(props) => <Dashboard {...props} isAuthed={true} />}
/>

这是我当前的代码。

<table>
  <tr>
    <th>id</th>
    <th>name</th>
    <th>username</th>
    <th>email</th>
    <th>delete</th>
  </tr>
  <tr *ngFor="let user of users">
    <td>
      {{ user.id }}
    </td>
    <td>
      {{ user.name }}
    </td>
    <td>
      {{ user.username }}
    </td>
    <td>
      {{ user.email }}
    </td>
    <td>
      <!-- <input type="checkbox" /> -->
      <button (click)="handleDeleteUser(user)">DEL</button>
    </td>
    <td>
      <button [routerLink]="['/edit', user]"> <-- problem here
        EDIT
      </button>
    </td>
  </tr>
</table>
/edit网址上

,将填充user obj。我不想同时传递ID和从后端进行查询,因为数据已经存在,我只需要传递它即可。有办法吗?谢谢

1 个答案:

答案 0 :(得分:1)

如果要与其他页面共享对象,则确实可以使用服务。

这个想法非常简单-将用户传递给某种服务,然后导航到页面。 该页面在加载时将从服务中获取用户。

interface User {
    id: number;
    name: string;
    surname: string;
    email: string;
}

@Injectable({providedIn: 'root'})
export class ActiveUserProvider {
    private _user: User;

    public get user(): User {
        return this._user;
    }

    public set user(value: User) {
        this._user = user;
    }
}

我们可以使用表格和编辑按钮在您的组件中注入此服务:

@Component()
export class TableComponent {
    // inject the service
    constructor(
        private activeUser: ActiveUserProvider,
        private router: Router)
    {}

    goToEditPage(user: User) {
        this.activeUser.user = user;
        this.router.navigate(['edit']);
    }
}

只需单击按钮即可调用goToEditPage方法:

<button (click)="goToEditPage(user)">EDIT</button>

然后您的编辑页面将如下所示

@Component()
export class EditUserComponent implements OnInit {
    public user: User;

    constructor(private activeUser: ActiveUserProvider) {}

    public ngOnInit() {
        this.user = this.activeUser.user;
    }
}

此方法的一些优点:

  1. 具有严格类型的单独服务,以帮助控制组件之间共享的内容
  2. 由于它是一项单独的可注入服务,因此我们现在可以轻松地分别测试这两个组件:我们可以测试表组件是否将活动用户设置为“编辑”点击;我们还可以测试是否在初始化时使编辑组件获得了活动用户。
相关问题