По сути, я хочу иметь понятные человеку названия маршрутов вместо длинного mongooseid в URL.
Например: вместо: https://localhost/campgrounds/50341373e894ad16347efe01
Я хочу: https://localhost/campgrounds/mountain-view
, где "гора-вид" будет названием кемпинга, который пользователь вводит в поле формы.
Это мой интерфейс:
campgrounds.model.ts
export interface Campground {
_id: String;
name: String;
routeURL: String;
description: String;
cost: Number;
}
campground-create.component.html (я не публикую другие поля формы, поскольку здесь нет необходимости)
<div class="container">
<form>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name"
[(ngModel)]="campground.name" (blur)="generateURL()" required>
</div>
<button type="submit" class="btn btn-primary"
(click)="addCampground()">Submit</button>
</form>
</div>
campground-create.component.ts
Это просто преобразует название палаточного лагеря, которое пользователь ввел в поле формы, и добавляет дефис между словами когда (blur).
import { Component, OnInit } from '@angular/core';
import { CampgroundService } from 'src/app/campground.service';
import { Router } from '@angular/router';
import { Campground } from 'src/app/campground.model';
@Component({
selector: 'app-campground-create',
templateUrl: './campground-create.component.html',
styleUrls: ['./campground-create.component.sass']
})
export class CampgroundCreateComponent implements OnInit {
campground: Campground = {} as Campground;
constructor(private campgroundService: CampgroundService, private
router: Router) { }
ngOnInit() {
}
generateURL() {
this.campground.routeURL = this.campground.name.toLowerCase()
.trim().split(/\s+/).join('-');
// Retrieve campground name and add hyphens between words
}
addCampground() {
this.campgroundService.addCampground(this.campground)
.subscribe(()=> {
this.generateURL();
this.router.navigate(['/campground-list']);
});
}
}
campground-list.component.html
<div class="background">
<header class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4 title">Welcome to YelpCamp!</h1>
<button type="button" [routerLink]="['/campground-create']"
class="btn btn-default btn-lg">Add New Campground</button>
</div>
</header>
<div class="card-deck">
<div class="card" *ngFor="let campground of campgrounds">
<img class="card-img-top" src="{{campground?.imageURL}}" alt="Card
image cap">
<div class="card-body">
<h5 class="card-title">{{campground?.name}}</h5>
<button type="button" routerLink="/campground-
details/{{campground.routeURL}}"
class="btn btn-danger">More Info</button>
</div>
</div>
</div>
</div>
Однако данные из службы не возвращаются обратно в лагерьстраница сведений, потому что я использую "findById".
campground-rout.js
router.get('/api/campground/:id', (req, res) => {
Campground.findById(req.params.id, (err, campground) => {
if (err) {
console.log(err);
} else {
res.json(campground);
}
});
});
, если у меня был идентификатор mongooseв маршруте сработало бы следующее:
campground-details.component.ts
import { Component, OnInit } from '@angular/core';
import { CampgroundService } from 'src/app/campground.service';
import { ActivatedRoute } from '@angular/router';
import { Campground } from 'src/app/campground.model';
@Component({
selector: 'app-campground-details',
templateUrl: './campground-details.component.html',
styleUrls: ['./campground-details.component.sass']
})
export class CampgroundDetailsComponent implements OnInit {
campground: Campground;
constructor(private campgroundService: CampgroundService, private
router: ActivatedRoute) {
}
ngOnInit() {
this.router.params.subscribe(params => {
const id = params['id'];
this.campgroundService.getCampground(id).subscribe(campground=> {
this.campground = campground;
console.log(this.campground);
});
});
}
}
Есть ли способ сделать это?Если да, есть ли простой способ сделать это?Спасибо.