typescript 喜欢查看被写在数组中的单个帖子

ezykj2lf  于 2023-01-03  发布在  TypeScript
关注(0)|答案(1)|浏览(60)

我有一个PostService和BlogPost,喜欢在我的html站点中使用url参数查看帖子。
本服务是:

export class PostService {

    posts = [
        {
        id: '1',
        title: 'this title',
        url: 'this-title',
        body: 'this body'
        }
    ]
    
    constructor() {
        const local_posts = localStorage.getItem('posts');
        if (local_posts) {
        this.posts = JSON.parse(local_posts);
        } else {
        localStorage.setItem('posts', JSON.stringify(this.posts));
        }
    }
    
    getList() {
        return this.posts;
    }
    
    get(id: string) {
        return { ...this.posts.find(p => p.id === id) };
    }
    
    getBy(url?: string) {
        return { ...this.posts.find(p => p.url === url) };
    }
}

而在我的博客我有错误:
成员"post"隐式具有"any"类型

export class BlogPostComponent implements OnInit {

post;   // Here is the problem

constructor(private route: ActivatedRoute, private router: Router, private postService: PostService) { }

ngOnInit() {
    this.route.params.subscribe(params => {
        this.post = this.postService.getBy(params['url'])

        if (!this.post.id) {
            this.router.navigate(['/not-found-page']);
        }
    })

}
}

我试着设定

post = new Array;

post = new Object;

但这行不通。
你有办法吗?
我现在添加了"noImplicitAny":但我认为这只是解决此问题的第二种方法。

vhipe2zx

vhipe2zx1#

定义BlogPost接口

export interface BlogPost {
  id:string;
  title: string;
  url:strign;
  body:stiring;
}

并将属性定义为BlogPost类型

export class BlogPostComponent implements OnInit {
post?: BlogPost;
//....
}

并重构服务以使用BlogPost接口

export class PostService {

    posts: BlogPost[] = [
        {
        id: '1',
        title: 'this title',
        url: 'this-title',
        body: 'this body'
        }
    ]
    
    constructor() {
        const local_posts = localStorage.getItem('posts');
        if (local_posts) {
        this. Posts = JSON.parse(local_posts);
        } else {
        localStorage.setItem('posts', JSON.stringify(this.posts));
        }
    }
    
    getList():BlogPost[] {
        return this.posts;
    }
    
    get(id: string) : BlogPost| null {
        return this.posts.find(p => p.id === id);
    }
    
    getBy(url?: string) : BlogPost| null {
        return this.posts.find(p => p.url === url);
    }
}

相关问题