在 React Router 中传递动态对象

Passing dynamic objects in React Router

如何在Angular 7.2.4 中传递动态数据?我一直在研究这个,但我没有看到简单的答案。在 SO 和 Github 上,他们说要创建共享服务,请在 Routes 上使用 data 对象。似乎 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 url,user obj 将填充。我不想传递 ID 也不想从后端进行查询,因为数据已经存在我只需要传递它。有办法吗?

如果您想与不同的页面共享对象,您确实可以使用服务。

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

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;
    }
}

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

@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. 因为它是一个单独的注入table服务,我们现在可以轻松地分别测试这两个组件:我们可以测试 table 组件在 "edit" 点击时设置活动用户;我们还可以测试编辑组件是否在初始化时获得活动用户。