Angular 相對路徑

前言

在上週恰好看到《相對與絕對路徑》這一節,剛開始看也沒細細研究,就按着教程走一遍,直到後來看到了本節小測:
image.png
原本心想,TeacherAddComponent模塊的跳轉都擺在這了,這不就是照着寫的事嗎。app

錯誤

先來看一下add(增長)按鈕的跳轉吧:
Peek 2019-12-06 16-56.gif
注意觀察URL的變化,先是由 Teacher 跳轉到 Teacher/add ,在點擊「提交」後,又由 Teacher/add 跳轉到 Teacher ,看一下具體的代碼:post

public onSubmit(): void {
    const url = 'http://localhost:8080/Teacher';
    const teacher = {
      name: this.name,
      username: this.username,
      email: this.email,
      sex: this.sex
    };
console.log(teacher);
this.httpClient.post(url,teacher)
  .subscribe(() =>{
    console.log('添加成功');
    this.appComponent.ngOnInit();
    this.router.navigate(['./../'],{relativeTo:this.route});

  },(response)=>{
    this.showMessage('請求發生錯誤');
    console.log('請求發生錯誤',response);
    });
  }
navigate(array, {}),接收的第二個參數爲對象,對象中的屬性relativeTo規定了跳轉的相對路由

對於上面的代碼來講,相對路由是本路由,也就是 Teacher/add this

./當前路徑 ../上級路徑,./../當前路徑的上級路徑。

當前路徑爲teacher/add時,當前路徑的上級路徑爲teacher
這就是啊addComponent跳轉的機制,順着這個思路,editComponent也就不難了,說幹就幹url

onSubmit():void{
  this.httpClient.put(this.getUrl(),this.teacher)
    .subscribe(()=>{
      console.log('更新成功');
      this.appComponent.ngOnInit();
      this.router.navigate(['./../'],{relativeTo:this.route});
    },
      ()=>
      {
        console.error('更新數據時發生錯誤,url:${this.getUrl()}');
      });
  }

理解的是這樣:Teacher/edit,當前路徑的上一級路徑就是Teacher,而後打開界面進行實踐:
Peek 2019-12-06 19-06.gifspa

解決

果真仍是不能太過相信直覺,既然出錯誤了,那就打開後臺瞅瞅:
image.png
因爲在跳轉以前的方法是沒有錯誤的,所以數據成功更新,因此會出現「更新成功」的字樣,之因此會報錯,是由於路徑 Teacher/edit 沒有找到,這與個人設想差了好多,而後看了一下路徑的變化:
image.pngcode


image.png


如今路徑多的除了 edit 還有一個數字,也就是id,那麼當前路徑就是Teacher/edit/id, 那麼當前路徑的上一級路徑就是Teacher/edit,可是,在路由的設置文件中,是沒有這個路徑的,因此控制檯會報錯.component

const routes: Routes = [
  {
    path: 'teacher',
    component:TeacherIndexComponent
  },
  {
    path:'teacher/add',
    component: TeacherAddComponent
  },
  {
    path:'teacher/edit/:id',
    component:TeacherEditComponent
  },
  {
    path:'klass',
    component:IndexComponent
  }
];

既然上一級是Teacher/edit,Teacher/edit 的上一級是Teacher,那就再加一個「../」router

Peek 2019-12-06 19-06.gif

問題成功解決對象

總結

本覺得相對路徑不把參數考慮在內,可是覺得就是覺得,不通過實踐真的沒法知道對錯,正遇上最近馬原考試,刷到不少有關於認識與實踐的題,
這些題的大體意思就是說科學的認識是以實踐爲基礎的,實踐是檢驗認識正確性的惟一標準,因此說不能眼高手低,要多實踐,多動手,尤爲對於敲代碼來講,更是這樣.blog

相關文章
相關標籤/搜索