我想在路由器导航到目标组件期间传递对象。目前我正在使用routeParams 并将我的对象字符串化为字符串。这种方法有效,但我不喜欢这种解决方案。更好的解决方案是什么样的?
export class Overview {
//import {Router} from "@angular/router-deprecated";
constructor(private router:Router) {}
goToElementComponent(elem:Element) {
this.router.navigate(['ElementDetail', {elem: JSON.stringify(elem)}]);
}
}
export class ElementDetail {
// import {RouteParams, Router} from "@angular/router-deprecated";
this.elem : Element;
constructor(private routeParams:RouteParams) {}
ngOnInit() {
var elem = JSON.parse(this.routeParams.get("elem"));
if (elem) {
this.elem = elem;
} else {
this.elem = new Element();
}
}
}
Run Code Online (Sandbox Code Playgroud) 我仍在使用 alpha8 路由器。我有3条主要路线:
export const appRoutes: RouterConfig = [
{ path: '', component: LandingComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'posts/:id', component: PostComponent },
{ path: 'posts', redirectTo: 'blog' },
{ path: '**', redirectTo: ''}
];
Run Code Online (Sandbox Code Playgroud)
因此,我有一个包含特色帖子和链接的组件,在 BlogComponent 中工作得很好,但是当该组件位于 PostComponent 中时,id 只会更改 url 地址。这就是该组件中链接的样子
<a [routerLink]="['/posts/'+post.id]">...</a>
所以当我们到达时,localhost:5000/blog它的路线很好到localhost:5000/posts/19f.ex。但从localhost:5000/posts/19它不去localhost:5000/posts/20。它只改变url,contstructor不ngOnInit执行。我怎么解决这个问题?
我在 typeScript 和 Angular 2 中遇到问题。我的 TS 类如下所示,
'import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-blogdetail',
templateUrl: './blogdetail.component.html',
styleUrls: ['./blogdetail.component.css']
})
export class BlogdetailComponent implements OnInit {
blogId:any;
title:any;
constructor(private _activatedRoute:ActivatedRoute) {
//Does not work
// this.blogId = this._activatedRoute.snapshot.params['id'];
//this.title= `This is blog detail for blogID:${this.blogId}`;
}
ngOnInit() {
this.blogId = this._activatedRoute.snapshot.params['id'];
this.title= `This is blog detail for blogID:${this.blogId}`;
}
}'
Run Code Online (Sandbox Code Playgroud)
我必须在 ngOnit 事件中获取路由参数。当我最初在 TS 类构造函数中使用相同的代码(获取参数)时,我得到的 blogId 变量值为undefined。据我了解事件的顺序,它们类似于下图,![flow] https://i.stack.imgur.com/41fpe.png
我们是否必须始终获取 ngOnIt 中的activatedRoute快照值?
产品服务.ts
getProduct(id: number): Observable<IProduct> {
return this._http.get(this._productUrl + '/GetById/' +
id).map((response: Response) => <IProduct>response.json())
.catch(this.errorHandler);
}
Run Code Online (Sandbox Code Playgroud)
产品详细信息组件.ts
getProduct(id: number) {
this._productService.getProduct(id).subscribe(
res => {
console.log('before component ' + res);
this.product = res;
console.log('after component ' + res);
},
error => this.errorMessage = <any>error),
console.log('execution complete');
}
Run Code Online (Sandbox Code Playgroud)
当在订阅中接收结果时,它会在
执行完成时出现,在组件 [object Object] 之前,在组件 [object Object] 之后
angularjs-directive angular-services angular2-routing angular
我有一个主要的app.routing.module.ts:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(routes),
],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Run Code Online (Sandbox Code Playgroud)
然后是几个子路由模块:
const routes: Routes = [
{ path: 'AbcRoute1', component: AbcRoute1Component },
{ path: 'AbcRoute2', component: AbcRoute2Component }
];
@NgModule({
imports: [ RouterModule.forChild(routes) ],
exports: [ RouterModule ]
})
export class AbcRoutingModule {}
const routes: Routes = …Run Code Online (Sandbox Code Playgroud) 我有一系列位于元素内部的输入框,我想让输入框的父元素根据鼠标的聚焦位置单独设置一个边框。代码如下所示:
HTML(只是输入元素之一,因为它们都以相同的方式编码):
<div class="parent-element">
<input type="text"
[class.bordered]="myBooleanVariable"
(focus)="addBorder()"
(blur)="removeBorder()"
/>
</div>
Run Code Online (Sandbox Code Playgroud)
打字稿:
addBorder() {
this.myBooleanVariable = true;
}
removeBorder(event) {
this.myBooleanVariable = false;
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,当在bordered上应用该类时focus,所有.parent-elementdiv 都会获得边框,因为myBooleanVariable它要么是 true,要么是 false。我希望避免静态变量一样myBooleanVariable1,myBooleanVariable2等
我怎样才能做到这一点?
每次路线更改都会渲染正确的组件,但路径存在问题。
例如,从 /items 导航到 /add-item 更改和 url 一秒钟,然后恢复它。
无论从哪里开始,到哪里去,它都会发生在每一页上。
导航
<a routerLink="/add-item">Add item</a>
Run Code Online (Sandbox Code Playgroud)
主要app.routes.ts
export const appRoutes: Routes = [{
path: 'brokers',
pathMatch: 'full',
redirectTo: '/'
},
{
path: 'sellers',
pathMatch: 'full',
redirectTo: '/'
},
{
path: 'buyers',
pathMatch: 'full',
redirectTo: '/'
},
{
data: { name: 'pageNotFound' },
path: '**',
redirectTo: '/404'
}];
Run Code Online (Sandbox Code Playgroud)
主页.routes.ts
export const homeRoutes: Routes = [{
component: HomePageComponent,
data: { name: 'homePage' },
path: ''
}
Run Code Online (Sandbox Code Playgroud)
页面未找到.routes.ts
export const pageNotFoundRoutes: Routes = [{
component: PageNotFoundComponent, …Run Code Online (Sandbox Code Playgroud) 我正在使用 Angular,这是用于我的身份验证检查:
export class EnsureAuthenticated implements CanActivate {
constructor(private auth: AuthService, private router: Router) {}
canActivate(): boolean {
if (localStorage.getItem('token')) {
return true;
}
else {
this.router.navigateByUrl('/login');
return false;
}
}
}
{
path: 'path',
component: myComponent,
canActivate: [EnsureAuthenticated]
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我的问题是用户和管理员都可以访问此页面。
我知道我没有设置任何条件。如何在其上设置适当的条件?
我不想让管理员访问此页面
有孩子路由器时怎么回到最后一页?
请参阅代码中的注释以获取详细信息 谢谢
export class OneProductComponent {
prevUrlPath:string = '';
constructor(private _router: Router) {}
routerOnActivate(next:ComponentInstruction, prev:ComponentInstruction) {
this.prevUrlPath = prev.urlPath;
}
goBack() {
// I have to manually add "products/" here, but if I need
// go back to root home page. Then I shouldn't add "products/" here.
// Is there a smart way to to this?
this._router.navigateByUrl(`products/${this.prevUrlPath}`);
}
}
Run Code Online (Sandbox Code Playgroud) 我最近将我的angular2应用程序从RC路由器切换到v3路由器.我收到了错误
TypeError: Cannot read property 'split' of undefined
at match`.
Run Code Online (Sandbox Code Playgroud)
在路由器上启用跟踪以获取调试输出后,看起来错误的来源来自路由器:
NavigationError {id: 2, url: "/my/workspace/1252407935628215305/projects", error: TypeError: Cannot read property 'split' of undefined
at match - common_router_providers.js:28 NavigationError {id: 2, url: "/my/workspace/1252407935628215305/projects", error: TypeError: Cannot read property 'split' of undefined
at match (http://localhost:8080/vendor.6a9d…}error: TypeError: Cannot read property 'split' of undefined
at match (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74100:22)
at matchPathsWithParamsAgainstRoute (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74073:19)
at expandPathsWithParamsAgainstRoute (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74038:17)
at expandPathsWithParams (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74020:21)
at matchPathsWithParamsAgainstRoute (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74085:23)
at expandPathsWithParamsAgainstRoute (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74038:17)
at expandPathsWithParams (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74020:21)
at expandSegment (http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74010:17)
at http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74014:84
at http://localhost:8080/vendor.6a9dd9122cbbc98aa93a.js:74367:41message: "Cannot …Run Code Online (Sandbox Code Playgroud) angular ×10
angular2-routing ×10
typescript ×5
angular5 ×1
angularjs ×1
javascript ×1
routes ×1