我对angular 2很新,并使用数据库中的帖子做一个简单的博客。我在后端使用nodejs + express从db获取数据。我有来自db的router-outlet中的帖子的帖子组件和来自db的post类别的单独的类别组件。我想要实现的是能够通过单击类别来筛选所选类别的帖子。有什么想法可以做到吗?
node.js routes.js的一部分
var comparer = new SequenceComparer();
var pivot = data.ToLookup(r => rowHeaders.Select(i => r[i]), comparer)
.Select(g => g.ToLookup(c => colHeaders.Select(i => c[i]), c => c[valHeader], comparer));
foreach (var r in pivot)
Debug.Print(string.Join(", ", headerInfo.Select(h => "[" + string.Join(",", r[h]) + "]")));
post.component.html
app.get('/admin/posts', function (req, res) {
sess = req.session;
console.log('sess.userData', sess.userData);
if (!sess.userData) {
sess.userData = {
id: [someId],
email: [someEmail],
name: [someName]
};
}
if (sess.userData) {
//get all posts when user checked
Post.getAllPosts(function (err, rows, fields) {
if (err) throw err;
return res.json(rows);
})
} else {
res.redirect('/');
}
});
//get posts by category, admin mode
app.get('/admin/posts/:category', function (req, res) {
sess = req.session;
if (!sess.userData) {
sess.userData = {
id: [someId],
email: [someEmail],
name: [someName]
};
}
if (sess.userData) {
//get all posts when user checked
Post.findByCategory(req.params.category, function (err, rows,
fields) {
searchedCategory = req.params.category;
existingCategory = rows[0].category;
if (rows.length && existingCategory === searchedCategory) {
// res.json(rows[0].tags);
return res.json(rows);
} else
return;
})
} else {
res.redirect('/');
}
});
//get all posts categories
app.get('/admin/post_categories', function (req, res) {
sess = req.session;
if (!sess.userData) {
sess.userData = {
id: [someId],
email: [someEmail],
name: [someName]
};
}
if (sess.userData) {
Post.getAllCategories(function (err, rows, fields) {
if (err) throw err;
return res.json(rows);
})
} else {
res.redirect('/');
}
});
post.service.ts
<article class="post-block">
<section *ngFor="let post of posts" class="post">
<article class="post__upper-block">
<section class="post__img">
<img class="post__img" src = "../../assets{{ post.titleImage }}" alt =
"post-img">
</section>
<section class="post__content">
<h2 class="post-title">{{ post.title }}</h2>
<p class="post-text">{{ post.shortContent }}</p>
</section>
<section class="post__operations">
<input type="button" value="Опубликован" class="post__btn post__btn--
active">
<input type="button" value="В работе" class="post__btn">
<input type="button" value="Редактировать" class="post__btn">
</section>
</article>
</section>
</article>
category.component.html
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PostService {
private _url = "http://localhost:3000/admin/posts";
constructor(private _http: Http) { }
getPosts(){
return this._http.get(this._url)
.map(res => res.json())
}
}
post.component.ts
import { Component, OnInit } from '@angular/core';
import { PostService } from '../../services/post.service';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.scss'],
providers: [PostService]
})
export class PostComponent implements OnInit {
posts: any[];
categories: any[];
constructor(private _postService: PostService) { }
ngOnInit() {
this._postService.getPosts()
.subscribe(posts => this.posts = posts);
}
}
category.service.ts
<article class="sidebar__categories">
<h3 class="categories-header">Разделы</h3>
<ul class="categories-ul">
<li *ngFor="let category of categories" class="categories-ul__item">
<a>{{ category.category }}</a>
</li>
</ul>
</article>
category.component.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CategoryService {
private _url = "http://localhost:3000/admin/post_categories";
constructor(private _http: Http) { }
getCategories(){
console.log("get-categories service works");
return this._http.get(this._url)
.map(res => res.json())
}
}
app.routes.ts
import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../../services/category.service';
import { PostService } from '../../services/post.service';
import 'rxjs/add/operator/map';
import { PostComponent } from '../post/post.component';
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.scss'],
providers: [CategoryService, PostService]
})
export class CategoriesComponent implements OnInit {
categories: any[];
posts: any[];
constructor(private _categoryService: CategoryService,
private _postService: PostService) { }
ngOnInit() {
this._categoryService.getCategories()
.subscribe(categories => this.categories = categories);
}
}
答案 0 :(得分:0)
您可以在Angular中创建自定义管道(过滤器),以下是您可以采用的方法。
1)Angular 2为PipeTransform接口提供了抽象变换方法。所以我们必须实现这个接口并覆盖自定义管道中的transform方法 (阅读更多https://angular.io/docs/ts/latest/guide/pipes.html) 2)使用Angular Cli并生成管道。
ng g pipe category
Your category.ts file will look bit similar to
import { Pipe, PipeTransform } from '@angular/core';
import { MyComponent } from './my/my.component';
@Pipe({
name: 'category'
})
export class CategoryPipe implements PipeTransform {
transform(value: any, args?: any): any {
let output: MyComponent[] = [];
// args will get passed on click
if(args!=='All') {
for( var i=0; i < value.length; i++) {
if(value[i].field_tags === args) {
output.push(value[i]);
}
}
} else {
output = value;
}
return output;
}
}
3) Editing your post.component.html ( Check *ngFor)
<article class="post-block">
<section *ngFor="let post of posts | category:blogcategory" class="post">
<article class="post__upper-block">
<section class="post__img">
<img class="post__img" src = "../../assets{{ post.titleImage }}" alt =
"post-img">
</section>
<section class="post__content">
<h2 class="post-title">{{ post.title }}</h2>
<p class="post-text">{{ post.shortContent }}</p>
</section>
<section class="post__operations">
<input type="button" value="Опубликован" class="post__btn post__btn--
active">
<input type="button" value="В работе" class="post__btn">
<input type="button" value="Редактировать" class="post__btn">
</section>
</article>
</section>
</article>
4) Edit category.component.html to update (ngFor to update variable filter)
<article class="sidebar__categories">
<h3 class="categories-header">Разделы</h3>
<ul class="categories-ul">
<li *ngFor="let category of categories" (click)="updateBlogCategory(filter)" class="categories-ul__item">
<a>{{ category.category }}</a>
</li>
</ul>
</article>
5) category.component.ts (added method updateBlogCategory)
import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../../services/category.service';
import { PostService } from '../../services/post.service';
import 'rxjs/add/operator/map';
import { PostComponent } from '../post/post.component';
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.scss'],
providers: [CategoryService, PostService]
})
export class CategoriesComponent implements OnInit {
categories: any[];
posts: any[];
constructor(private _categoryService: CategoryService,
private _postService: PostService) { }
ngOnInit() {
this._categoryService.getCategories()
.subscribe(categories => this.categories = categories);
}
updateBlogCategory(stringCategory: string) {
this.blogcategory = stringCategory;
}
}
我希望这会有所帮助。如果你可以创建plnkr,那么解释和编辑就会容易得多。