@kikosko

Почему не переходит по роуту отдельного элемента?

Я создал диалог с компонента: "GalleryItemComponent" где отображаю информацию о элементе, когда нажимаю на кнопку "edit" в диалоге, хочу переходить по роуту ":id" нужного мне элемента на компонент "GalleryItemComponent" где уже буду редактировать элемент. Но при переходе по нужному мне роуту, получаю такую вот ошибку: "Error: StaticInjectorError(AppModule)[MatDialogTitle -> MatDialogRef]:
StaticInjectorError(Platform: core)[MatDialogTitle -> MatDialogRef]:
NullInjectorError: No provider for MatDialogRef!". Пробовал добавить "MatDialogRef" в провайдеры "GalleryModule" в результате получал ошибку: "Can't resolve all parameters for MatDialogRef: (?, ?, ?). unit testing Angular ". Поясните пожалуйста, как перейти по роуту соответствующего id элемента.

GalleryRoutingModule:

const galleryRoutes: Routes = [
    {
        path: '',
        canActivate: [AuthGuard],
        children: [
            {path: '', component: GalleryComponent, resolve: {posts: PostsResolver}},
            {path: 'add', component: GalleryAddComponent},
            {path: ':id', component: GalleryItemComponent, resolve: {post: PostResolver}},
        ]
    },
];


PostResolver:

@Injectable({
    providedIn: 'root',
})

export class PostResolver implements Resolve<Picture> {
    constructor( private galleryService: GalleryService) {
    }
    resolve(route: ActivatedRouteSnapshot): Observable<Picture> {
        return this.galleryService.getPicture(+route.paramMap.get('id'));
    }
}


Gallery.component.ts:

export class GalleryComponent implements OnInit {
    collection: Picture[] = [];


    fileNameDialogRef: MatDialogRef<GalleryItemComponent>;

    constructor(private route: ActivatedRoute, private dialog: MatDialog) {
}
    ngOnInit() {
        this.getPictures();
    }
   getPictures() {
        this.route.data.subscribe(data => {
            data.posts.forEach(post => {
                if (post.id > 10) {
                    this.collection.unshift(post);
                } else {
                    this.collection.push(post);
                }
                this.save();
                this.getCollection();
            });
        })
    }

    openAddFileDialog(pic?) {
        this.fileNameDialogRef = this.dialog.open(GalleryItemComponent, {
            minWidth: 300,
            minHeight: 400,
            data: pic
        });
    }
}


Gallery.component.html:

<div class="row">
    <div class="col-lg-3 col-md-4 col-6" *ngFor="let pic of collection; ">
        <div class="info">
            <a [routerLink]="[pic.id]" >
                <img [src]="pic.url" alt="test" class="img-responsive">
                <p class="lead"><span>{{pic.id}}:</span>{{pic.title | truncate:'14':true}}</p>
            </a>
            </p>
        </div>
        <div class="card buttons">
            <button (click)="openAddFileDialog(pic)">Add file</button>
        </div>
    </div>
</div>


GalleryItem.component.html:

<div *ngIf="data" class="item">
        <div class="card  w-100">
            <h3 mat-dialog-title>About orc</h3>

                <img class="card-img-top" [src]="data.url" alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title">Orc number: {{data.id}}</h5>
                    <p class="card-text"><strong>What orc says about himself:</strong> {{data.title}}</p>

                    <p class="card-text"><strong>Orc birthday:</strong> <span class="date-info" [Highlight]>{{ data.date | date: 'fullDate'}}</span>
                    </p>
                </div>
            <mat-dialog-actions>
                <button routerLink="gallery/{{data.id}}">Edit</button>
            </mat-dialog-actions>
        </div>
    </div>
</mat-dialog-content>


GalleryItem.component.ts:

export class GalleryItemComponent implements OnInit {
   pic: Picture;

    constructor( private route: ActivatedRoute,
                 private dialogRef: MatDialogRef<GalleryItemComponent>,
                 @Inject(MAT_DIALOG_DATA) private data
                ) {

    }

    ngOnInit() {
        this.showPost();
    }

    showPost(): void {
        this.route.data.subscribe(params => {
            this.pic = params.post;
        })
    }
}
  • Вопрос задан
  • 193 просмотра
Пригласить эксперта
Ответы на вопрос 1
Qairat
@Qairat
frontend developer, angular 2+
Переход по роутам можно сделать так:
{ path: 'main', component: HelloComponent },
  { path: 'main/:id', component: HelloComponent },


[routerLink]="['../main', d.id]"

Перейди по ссылке

а то что у тебя ошибка, это не связано с роутами, там ошибка конкретно с MatDialogRef.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы