如何将redirectTo与包含参数的网址一起使用?

时间:2020-06-28 14:38:48

标签: angular routes angular9

我希望在路径为 import React, { useEffect } from 'react' import { useDispatch } from 'react-redux' import axios from 'axios' import { getItemsStart, getItemsSuccess, getItemsFailure } from '../features/itemsSlice' const fetchItems = () => async dispatch => { try { dispatch(getItemsStart()); const { data } = await axios.get('url/api') dispatch(getItemsSuccess(data)) } catch (error) { dispatch(getItemsFailure(error)) } } const PageA = () => { const dispatch = useDispatch() const { items } = useSelector(state => state.dataSlice) useEffect(() => { dispatch(fetchItems()) }, [dispatch]) return ( <ul> {items.map(item => <li>{item.name}</li>} </ul> ) } export default PageA 时将用户重定向到相对路径':lang/home'。但是,当我导航到''时,HomeComponent将不会加载。

这是代码段:

localhost:4200/

仅当我用诸如const routes: Routes = [ { path: '', redirectTo: ':lang/home', pathMatch: 'full' }, 之类的硬编码语言代码替换:lang时,此方法才有效。 我已经尝试过en/homelocalhost:4200/:lang/home,但这都不起作用。 两者都给浏览器错误:

/:lang/home

我该如何解决?谢谢

1 个答案:

答案 0 :(得分:0)

建立巡逻队,

@Injectable()
export class HomePageRedirect implements CanActivate {
    canActivate() {
        //Your redirect logic
    
    if (this.user && this.user.lang) {
     this.router.navigate([this.user.lang,"home"]);
    }
    return true;
}
//Constructor 
constructor(private router: Router) { }
}

在您的路线上,

  { path: '' pathMatch: 'full', component: HomeComponent, canActivate:[HomePageRedirect] },