到目前为止,我试图通过按钮点击来循环显示图像,但不是在我发布的代码中。我尝试了一种无效的路由方法,所以我删除了我的代码。如果有人可以展示或提供有关如何解决这个问题的任何建议。
我的目标是,每当用户点击下一个或上一个按钮时,网址都应该更新,从而更改为下一个图像。
例如,网址为http://localhost:4200/image/8,如果用户点击后退或前进按钮,则网址将分别更新为http://localhost:4200/image/7或http://localhost:4200/image/9,从而更改图片屏幕。
下面,您将找到我的HTML代码片段graph.service.ts
文件的片段,其中包含所有图像的数组,以及我的metric.component.ts
文件,我尝试获取{{1}图表并显示它们。
ids
<div class = "row">
<button class="previous round">‹</button>
<div [ngStyle] = "{'background-image': 'url('+ graph.url +')'}" class ="img-container">
</div>
<button class="next round">›</button>
</div>
&#13;
import { Injectable } from '@angular/core';
@Injectable()
export class GraphService {
constructor() { }
getGraph(id: number){
return GRAPHS.slice(0).find(graph => graph.id == id)
}
}
const GRAPHS = [
{id: 1, catergory: "Popularity", url: "assets/img/pgraph.jpg" },
{id: 2, catergory: "releasefrequency", url: "assets/img/rqgraph.jpg" },
{id: 3, catergory: "lmd", url: "assets/img/lmd.jpg" },
{id: 5, catergory: "last discuss overflow", url: "assets/img/ldof.png" },
{id: 6, catergory: "performance", url: "assets/img/performance.jpg" },
{id: 7, catergory: "security", url: "assets/img/security.jpg" },
{id: 8, catergory: "responsetime", url: "assets/img/responsetime.png" },
{id: 9, catergory: "closingtime", url: "assets/img/isueclosing.png" }
];
&#13;
答案 0 :(得分:2)
您必须订阅参数更改并更新组件中的activeId
。您不能依赖snapshot
值,因为params将在创建组件后更改,并且如果仅更改了params,路由器将不会重新创建组件。因此,ngOnInit
和constructor
只会运行一次。
这是一个反应性的例子。我没有为图片使用单独的服务,但可以随意将任何内容提取到单独的服务中。
import { Component, Input } from '@angular/core';
import { ActivatedRoute, Router} from '@angular/router';
import { map } from 'rxjs/operators';
@Component({
selector: 'hello',
template: `
<div> {{ activeImage }} </div>
<button (click)="prev()">Prev</button>
<button (click)="next()">Next</button>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class ImagesComponent {
images = [
'first image',
'second image',
'third image'
]
activeId = 0;
get activeImage() {
return this.images[this.activeId];
}
constructor(private activatedRoute: ActivatedRoute, private router: Router) {}
ngOnInit() {
this.activatedRoute.paramMap.pipe(
map((params) => params.get('id') || 0),
map(n => Number(n))
).subscribe(id => this.activeId = id);
}
next() {
const next = this.activeId + 1 >= this.images.length - 1 ? this.images.length -1 : this.activeId + 1;
this.router.navigate([next])
}
prev() {
const prev = this.activeId - 1 < 0 ? 0 : this.activeId - 1;
this.router.navigate([prev])
}
}
该示例假定以下路由配置:
RouterModule.forRoot([
{ path: '', redirectTo:'0', pathMatch: 'full' },
{ path: ':id', component: ImagesComponent }
])