【问题标题】:How to create a blog category in angular 7如何在 Angular 7 中创建博客类别
【发布时间】:2019-09-30 14:28:00
【问题描述】:

我能够从 phpmyadmin 数据库中获取博客类别名称。 我要链接分类名称

categories.component.html:


    <div class="right-widget categories">
        <h3>Categories</h3>
        <ul>
           <li *ngFor="let category of categories">
             {{category.name}}
          </li>
       </ul>
      </div>

blogpost.service.ts:

export class BlogpostService {
  getFeaturedBlogs() {
    throw new Error("Method not implemented.");
  }

  ServerUrl = 'http://localhost/demo/blogger/';
  errorData: {};

  constructor(private http: HttpClient) { }

  getBlog(id: number) {
    return this.http.get<Blogpost>(this.ServerUrl + 'api/blog/' + id)
    .pipe(
      catchError(this.handleError)
    );
}

getRecentBlogs() {
    return this.http.get<Blogpost>(this.ServerUrl + 'api/recent_blogs').pipe(
      catchError(this.handleError)
    );
}

getCategories() {
    return this.http.get<Category>(this.ServerUrl + 'api/categories').pipe(
      catchError(this.handleError)
    );
}

categories.component.ts
export class CategoriesComponent implements OnInit {

      categories: Category;
      error: {};

      constructor(private blogpostService: BlogpostService) { }

      ngOnInit() {
        this.blogpostService.getCategories().subscribe(
          (data: Category) => this.categories = data,
          error => this.error = error
          );
      }
    }

你能帮帮我吗?我无法关联类别名称?

【问题讨论】:

  • 我没有看到你在任何地方定义属性categories
  • 我认为您想将响应类型转换为 Category 数组对象。如果您已将类别定义为类,则它将不起作用。您需要创建一个具有所需属性的接口。看到这个答案 - stackoverflow.com/a/58154215/5396181

标签: angular


【解决方案1】:

我想你有一个文件 categories.component.ts。

在这个文件的构造函数中,你注入一个服务

constructor(private service: BlogpostService) {}

还有一个变量

categories: Category[];

然后,例如,在 ngOnInit 方法中, 您调用服务方法并获取类别数据

ngOnInit() {
 this.service.getCategories().subscribe(
   data => {
     this.categories = data
   }
 )
}

看起来 getCategories 返回一个数组。 如果是真的,你需要改变 getCategories() 方法

return this.http.get<Category>

return this.http.get<Category[]>

【讨论】:

  • 非常感谢您的回复。我已经更新了代码。你能检查一下上面提到的代码吗?
  • @PamuShinde 定义具有所需属性的类别接口。看看这个答案 - stackoverflow.com/a/58154215/5396181
  • 代码看起来不错。您能否也显示类别界面?在 categories.component.html 你迭代抛出类别,所以它需要是一个数组。但如果它是一个单一的对象,你就不能这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 2017-06-17
相关资源
最近更新 更多