【问题标题】:How to configure routes in Angular properly如何在 Angular 中正确配置路由
【发布时间】:2020-03-22 04:58:48
【问题描述】:

我正在学习 Angular 中的路由。我正在学习 Pluralsight 的一些教程。这是相同的stackblitz。我尝试了一个非常基本的代码来理解路由。但我收到了这个错误:

“模块'PostModule'声明的非预期值'PostList'。请添加@Pipe/@Directive/@Component注解。”

我调试了代码,这是罪魁祸首:

post-list.component.ts

import { PostService } from './post.service';

export class PostList {

  constrcutor(private postservice: PostService) {
    postservice.getAllPosts();
  }
}

我正在尝试阅读已经存储在某处的帖子(我正在使用 JSONPlaceholder)。我想在一个页面上显示所有帖子,然后在点击事件中我想导航到该特定帖子的详细信息。这是我的:

post.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  constructor() {}

  getAllPosts() {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => response.json())
      .then(json => console.log(json))
  }
}

这是我的: post.module.ts

import { NgModule } from '@angular/core';
import { PostDetails } from './post-details.component';
import { PostList } from './post-list.component';
import { RouterModule } from '@angular/router';

@NgModule({
  imports:[
    RouterModule.forChild([
      {path: 'posts', component: PostList},
      {path: 'posts/:id', component: PostDetails}
    ])
  ],
  declarations:[PostList, PostDetails]
})
export class PostModule {}

我的问题是路由。我无法正确设置路线。我为此创建了一个stackblitz。请指出我的错误。我真的很想通过所有最佳实践来学习 Angular。请纠正我。

【问题讨论】:

  • 对于 PostList 组件,没有 Component 装饰器来定义它是一个组件。

标签: angular angular-routing angular-routerlink


【解决方案1】:

您必须将@Component 添加到您的班级

import { PostService } from './post.service';

// added this below ↓
@Component({
  selector: 'whatever',
  templateUrl: './my-template.template.html',
})
export class PostList {

  constrcutor(private postservice: PostService) {
    postservice.getAllPosts();
  }
}

问题在于,由于您的类没有通过该组件装饰器,因此将其添加到 declarations 似乎您向 angular 添加了错误的东西,因为它只需要其中的组件(具有 @component)

编辑: 检查了您的 stackblitz 并修复了问题,但出于同样的原因,您在 PostDetails 声明中遇到了错误。请找到组件的选项并学习如何正确使用它,您需要将 @Component 装饰器添加到所有实例中,并且您必须为其添加选择器和模板(选择器是如何从 html 定位的,并且模板是组件 html 的内容),您可以使用 templateUrl 来定位另一个带有 html 的文件,您可以添加样式或 styleUrls 等......

希望对你有帮助,有什么问题可以继续追问

【讨论】:

  • 实际上我可以使用ng g c productList,但我决定从头开始编写代码,以便了解我在写什么以及我为什么写。下次我会更小心的。
  • 嘿,我自己也是作家……我所有的组件、指令和服务都是这样写的。我向你保证这是最好的学习方式(并避免自动创建不必要的代码)。继续这样做:您很快就会在这些问题发生之前看到它们。我支持你写这一切的方式!
  • 先生,最后一个问题。在我的 post.service.ts 中,您可以看到我创建了一个方法 getAllPosts(),它将从服务器获取帖子。那么在构造函数内部还是 ngOnInt 内部哪个是调用此方法的最佳位置?
  • 我问这个是因为稍后我将实现预取数据代码,这样用户就不会得到一个空页面。我将使用一些加载图标,直到从服务器。
  • 为了保持一致性,onInit 更有意义,因为它在组件构建后触发(构造函数在组件构建后触发它,但在将组件对象返回给应用程序之前,如果这有意义的话)。 ....因此,在您的特定情况下实际上可能没有区别,但很高兴知道它们发生在不同的时间...构造>绑定(onChanges)> onInit> afterViewInit ...等,这些生命周期钩子如果你忘记了,可以用谷歌搜索:) 我一直都忘记了
猜你喜欢
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多