My code seems to have a mistake somewhere, but I can't figure it out. In my
[queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
, the params object is empty when I subscribe to it in the edit-server component
. Why is it empty and how do I add allowEdit
to it? Maybe the issue lies in an incorrect path? Let me provide more details about relevant paths.
Here is the code snippet:
ServerS Template
<a
[routerLink] = "['/servers', server.id]"
[queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
href="#"
class="list-group-item"
*ngFor="let server of servers">
{{ server.name }}
</a>
<router-outlet></router-outlet>
Server Template:
<h5>{{ server.name }}</h5>
<p>Server status is {{ server.status }}</p>
<button class="btn btn-primary" (click)="onEdit()">Edit Server</button>
Server TS:
export class ServerComponent implements OnInit {
server: {id: number, name: string, status: string};
id: number
constructor(private serversService: ServersService, private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.id = +this.route.snapshot.params['id']
this.server = this.serversService.getServer(this.id)
this.route.params.subscribe((params: Params) => {
this.server = this.serversService.getServer(this.id)
})
}
onEdit() {
this.router.navigate(['edit'], {relativeTo: this.route})
}
}
Edit Server TS:
export class EditServerComponent implements OnInit {
server: {id: number, name: string, status: string};
serverName = '';
serverStatus = '';
allowEdit: boolean
constructor(private serversService: ServersService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.snapshot.queryParams
this.route.snapshot.fragment
this.route.queryParams.subscribe((params: Params) => {
console.log(params['allowEdit']) // for some reason, params['allowEdit'] gives us undefined
this.allowEdit = params['allowEdit'] == 1 ? true : false
})
this.route.fragment.subscribe((params: string) => {
})
//
this.server = this.serversService.getServer(1);
this.serverName = this.server.name;
this.serverStatus = this.server.status;
}
}
Please note that some code blocks may be irrelevant, but if you need more information, feel free to ask. Here's my folder structure and AppModule paths for reference.
App Module:
const appRoutes: Routes = [
{
path: 'users',
component: UsersComponent,
children: [ {
path: 'users/:id/:name',
component: UserComponent
}]
},
{
path: '',
component: HomeComponent
},
// The ones below are the important ones
{
path: 'servers',
component: ServersComponent,
children: [ {
path: ':id/edit',
component: EditServerComponent
},
{
path: ':id',
component: ServerComponent
}]
},
]
Relevant Folder Structure