简体   繁体   English

无法使用 angular 访问属性

[英]Can't access properties with angular

I am trying to display properties from data but it doesn't work & i don't understand why.我试图从数据中显示属性,但它不起作用,我不明白为什么。 No error in the console.控制台中没有错误。

My component:我的组件:

export class BlogpostComponent implements OnInit {
blogpost$: Observable<BlogPost>;
id;
blogsId;

constructor(private activatedRoute: ActivatedRoute, private blogpostService: BlogpostService) {}

getBlog(id) {
    this.id = id;
    id = this.activatedRoute.snapshot.paramMap.get('id');
    console.log('id', id);
    this.blogpost$ = this.blogpostService.getPost(id);
    console.log('blogpost', this.blogpost$);
}

ngOnInit() {
    this.getBlog(this.id);
    console.log('OBS', this.blogpost$);
}

my view:我的看法:

<div>{{ blogpost$ | async | json }}</div>
<ng-container *ngIf="blogpost$ | async as bp; else loading">
  <div
  class="card text-white bg-secondary mb-3" 
  style="max-width: 18rem;"
  >
  <div class="card-header">{{ bp.content }}</div>
  <div class="card-body">
    <h5 class="card-title">Hello there</h5>
    <p class="card-text">
      Hello text
    </p>
  </div>
</div>
</ng-container>

<ng-template #loading>Loading post ...</ng-template>

my service:我的服务:

@Injectable({
  providedIn: "root"
})
export class BlogpostService {
  url = "http://localhost:3000";

  constructor(private httpClient: HttpClient) {}

  getAllPosts(): Observable<BlogPost[]> {
    return this.httpClient.get<BlogPost[]>(`${this.url}/allblogs`);
  }

  getPost(id): Observable<BlogPost> {
    return this.httpClient.get<BlogPost>(`${this.url}/blog/${id}`);
  }
}

this <div>{{ blogpost$ | async | json }}</div>这个<div>{{ blogpost$ | async | json }}</div> <div>{{ blogpost$ | async | json }}</div> <div>{{ blogpost$ | async | json }}</div> print the json with all properties as it should. <div>{{ blogpost$ | async | json }}</div>打印具有所有属性的 json。

But when i call properties in my view {{ bp.content }} , i've nothing displayed.但是当我在视图中调用属性{{ bp.content }} ,我没有显示任何内容。

Thanks for your help.谢谢你的帮助。

Problem seems to be that blogPost$ is being set to an array of blog posts instead of an object, that's why {{ bp.content }} is not displaying anything.问题似乎是blogPost$被设置为一组博客文章而不是一个对象,这就是为什么{{ bp.content }}不显示任何内容。

Even though BlogPost is defined as an object instead of an array, at runtime, you can still assign an array to the variable which is what is happening here.即使BlogPost被定义为对象而不是数组,在运行时,您仍然可以将数组分配给变量,这就是这里发生的事情。

I can't see where you've defined bp .我看不到你在哪里定义bp So you should either define it or replace it with the defined one blogpost .所以你应该定义它或用定义的一篇blogpost替换它。

Update After finding the definition as alias in the HTML I would try to do bp?.content .更新在 HTML 中找到别名的定义后,我会尝试执行bp?.content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM