0

I'm having an object from an API where I want to display the dynamic values in the value field of a form in Angular.

TS2339: Property 'title' does not exist on type 'Object'.

HTML:

      <h1>Edit News Post</h1>
      <form>
        <div class="form-group" >
          <label for="newsTitle">Title</label>
          <input id="newsTitle" type="text" class="form-control" value="{{ news.title }}">
        </div>
</form>

component.ts:

export class NyheterEditComponent implements OnInit {
  news: Object = [];

  constructor(private http: HttpClient, private postsService: PostsService, private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    console.log(this.route.snapshot.paramMap.get('id'));
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.postsService.fetchNewsItem(id).subscribe(response => {
      console.log(response);
      this.news = response;
  })
  }

The object I'm trying to access is displaying in the console as:

{
  id: 4, 
  title: 'Zebrapower', 
  description: 'Sebra som en Sebra', 
  image_path: 'https://images.unsplash.com/photo-1646206924799-c9…lfHx8fGVufDB8fHx8&auto=format&fit=crop&w=884&q=80', 
  active: true
}

I bet it's just a silly mistake, but I can't access it no matter what I try!

EDIT: Added fetchNewsItem from posts.service.ts

  fetchNewsItem(id: number) {
    const options = {headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      params: {
        id: id,
      },
    };
    return this.http.get('https://infoboard-api.setpoint.no/infoboard/news/news-by-id', options)
  }
1
  • You're using TypeScript; use types. Specify a type for news, like { id: number; title: string; description: string; image_path: string; active: boolean; }. Commented Mar 7, 2022 at 14:35

1 Answer 1

1

There are a number things about your code that make things a bit unclear.

Your property news is declared as type Object, but you are assigning an empty array to it as the initial value. The response object you are assigning to it based on the api response is an object though.

As for your error, the JavaScript type Object doesn't have a property title on it which is why you are seeing the error you are. Ideally, you would create an interface or class to represent the return type from the api and declare your property as such, such as:

export public interface NewsItem {
  id: number;
  title: string;
  description: string;
  image_path: string;
  active: boolean;
}
export class NyheterEditComponent implements OnInit {
  news: NewsItem;

  constructor(private http: HttpClient, private postsService: PostsService, private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    console.log(this.route.snapshot.paramMap.get('id'));
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.postsService.fetchNewsItem(id).subscribe(response => {
      console.log(response);
      this.news = response;
  })
  }

While that will take care of your current 'build-time' error. You will most likely now get a run-time error because Angular will render the UI and the property news will have a value of undefined which will cause the rendering to error because you are trying to access the title property on an undefined value. The simplest way to fix that would be to use the null coalescing operator in your html template as follows:

<h1>Edit News Post</h1>
      <form>
        <div class="form-group" >
          <label for="newsTitle">Title</label>
          <input id="newsTitle" type="text" class="form-control" value="{{ news?.title }}">
        </div>
</form>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for clearing that up! I tried it like you said, but I got two new errors: ` nyheter-edit.component.ts:26:3 - error TS2564: Property 'news' has no initializer and is not definitely assigned in the constructor. 26 news: NewsItem; ~~~~ nyheter-edit.component.ts:36:7 - error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'NewsItem': id, title, description, image_path, active 36 this.news = response;`
1. You aren't sharing all of your code, so I have to guess. My assumption is that postsService.fetchNewsItem is typed to return an Object. That should also be updated to return NewsItem. 2. initializer issue can be cleared up in a few ways. Easiest would be to do the following: news: NewsItem | undefined;
Not sure why, I can't seem to edit my comment, but what I meant for number 2 is as follows: initializer issue can be cleared up in a few ways. Easiest would be to do the following: news?: NewsItem;
I added my fetchNewsItem in the original post I still get error on this.news = response: TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? Type 'Object' is missing the following properties from type 'NewsItem': id, title, description, image_path, active
Never mind, I got it to work :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.