Reputation: 4998
I'm learning Routes in Angular. I'm following some tutorials from Pluralsight. Here is the stackblitz for the same. I tried a very basic code to understand routing. But I'm getting this error:
"Unexpected value 'PostList' declared by the module 'PostModule'. Please add a @Pipe/@Directive/@Component annotation."
I debugged the code, and here's the culprit:
post-list.component.ts
import { PostService } from './post.service';
export class PostList {
constrcutor(private postservice: PostService) {
postservice.getAllPosts();
}
}
I'm trying to read posts which are already stored somewhere (I'm using JSONPlaceholder). I want to show all the posts on one page and then on click event I want to navigate into the details of that particular post. Here is my:
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))
}
}
and here's my: 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 {}
My problem is Routing. I'm not able to set routes correctly. I've created a stackblitz for the same. Please point out my mistakes. I really want to learn Angular with all best practices. Please correct me.
Upvotes: 0
Views: 50
Reputation: 1338
you have to add @Component
to your class
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();
}
}
The problem is that since your class is not being passed that component decorator, adding it to declarations
seems like you added the wrong thing to angular, since it only expects components in there (which have @component)
edit: checked your stackblitz and fixed the issue but then you get an error with the PostDetails declaration, for the same reasons. Please find the Component's options and learn how to use it properly, you need to add the @Component decorator to all instances, and you have to add a selector and template to it (selector is how is it going to be targeted from the html, and template is what the component html is), you can have templateUrl to target another file with the html, you can add styles or styleUrls, etc....
hope this helps, feel free to ask anything further
Upvotes: 3