你好,如何在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和从后端进行查询,因为数据已经存在,我只需要传递它即可。有办法吗?谢谢
答案 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;
}
}
此方法的一些优点: