Angular 2 throws a typescript error with code TS2339 stating that the property 'x' is not found on the type 'Y'

I'm having trouble converting an HTTP response into a DTO object. I can't seem to figure it out on my own and would appreciate some help with this issue.
I have a service that uses an adapter class to convert the response into an array of objects and then returns it to the controller. However, when trying to assign the HTTP service response to the controller variable, I receive an error: "error TS2339: Property 'collectionArray' does not exist on type 'Collection[]'".

DTO:

export class Collection {

private collectionId: number;
private image: string;
private url:string;
private title:string;
private description:string;

  static getCollection(responseData) {
    var obj = new Collection();
    obj.setCollection_id(responseData.collection_id);
    obj.setImage_url(responseData.image_url);
    obj.setUrl(responseData.url);
    obj.setTitle(responseData.title);
    obj.setDescription(responseData.description);
    return obj;
  };
//getter setter
}


   **Controller:**

        import { Collection } from '../model/collection';

        import {CollectionService} from './collection.service';

         public collections : Collection[] = [];

        //calling service
        this.collectionService.getCollection().subscribe(
              data => {
                 // giving error here
                 this.collections = data.collectionArray
              },
              err => {
                 console.log(err);
              });

        **service :** 

         getCollection() : Observable<Collection[]>{
                 // ...using get request
                 var options = new RequestOptions({
                    headers: new Headers({
                    'Accept': 'application/json',
                     'user-key' : '7d5ef14e15e096400df74871'
                    })
                  });
               return this.http.get(this.url, options)
              //returning arry of colletion object
                 .map((res:Response) =>  new CollectionAdapter(res.json()))
                   .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

                 }

        **Adapter:**

        export class CollectionAdapter{

            public collectionArray : Collection[] = [];

            constructor(responseData){
              this.getCollectionList(responseData.collections);
            };

            getCollectionList(response) {
                for (var collectionObj of response) {
                  let collObj = collectionObj.collection;
                  let obj = Collection.getCollection(collObj);
                  this.collectionArray.push(obj)
                }
                return this.collectionArray;
            };
          }

Answer №1

If you encounter a compilation error

it could be due to your service returning :

 getCollection() : Observable<Collection[]>

consider changing it to

 getCollection() : Observable<CollectionAdapter>

If the error occurs during runtime

utilize console.log(data) to inspect the output

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Jquery Mobile 1.4.5 virtual keyboard on the device is causing the form inputs at the bottom of the page to become hidden

I am currently working on a web app using JQuery Mobile 1.4.5. Encounter an issue that seems to be related to either the browser or JQM bug specifically when using Google Chrome in fullscreen mode on Android (v.4.4.2). Upon clicking on the Click Here!! ...

Validating Form Controls with Dynamic Names in Angular 5

Initially, I believed this task would be straightforward. The following snippet of HTML is functioning as anticipated: <label class="mb-0 form-label"> Doc Part </label> <input type="number" name="DocPart" #DocPart="ngModel" class="form- ...

Is there a way to prevent Faker from continuously displaying the identical picture?

One of the challenges I'm facing involves using faker to generate an array of random objects. Here's a snippet of what I have: { "image": faker.random.arrayElement([ faker.image.nature(), faker.image.city(), faker.image.food() ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

Error message encountered: "Unresolved ReferenceError while employing aframe-physics alongside ammo.js, npm, and webpack."

Summary: I am currently attempting to integrate ammo.js physics into an aframe project built with npm and webpack. The reason for needing ammo.js is because cannon.js relies on a deprecated .Geometry component from threejs. This integration must be done t ...

How to toggle the visibility of a div with multiple checkboxes using the iCheck plugin for jQuery

I customized my checkboxes using the icheck plugin to work with both single and multiple checkboxes, including a "Check all" option. Here is an example of how it looks in HTML: HTML : <div>Using Check all function</div> <div id="action" c ...

Trouble displaying events from resource in Angular UI calendar integration

I have encountered a perplexing issue with Angular UI Calendar. My goal is to fetch events from an API and display them on the calendar. Initially, the events load correctly when the page is first loaded. However, if I navigate to the next month and then r ...

Extract information from JSON using a filter

Is there a way to extract the data value from the list without relying on index positions, considering that the order of arrays can change? I need to specifically target data where code === "size". Unfortunately, the existing structure cannot be ...

Sequelize cannot locate the specified column in the database

click here for image description I encountered an issue where a column was not recognized after migrating with sequelize-cli. Even though all the columns are defined in the migration file, this error keeps appearing. Additionally, when trying to create a ...

Use the onClick attribute with Iframe

Is there a method to wrap an Iframe within another element to create a simulated onClick event? I am aware that Iframes do not support events, however, I require the ability to monitor clicks from my website that are being redirected through the Iframe. A ...

Unable to send HTML content back from the controller when making Ajax requests in a messaging application

Currently, I am in the process of developing an integrated chat application within CRM. The main functionality involves displaying the chat history between users when a logged-in user clicks on a contact using Ajax calls. However, I have encountered some i ...

Create a clear section within a div element

https://i.sstatic.net/TCp6E.jpg I'm looking to create a design similar to the image above using only 2 divs and an img. I was able to achieve it using 6 divs, but is there a way to make a transparent mapped area of the parent div with CSS or JavaScrip ...

What is the reason for the JSON Structure always displaying a numeric key first?

(The Challenge of Updating JSON Structure based on User Interaction) Utilizing Angular Typescript, I dynamically create a JSON structure that reflects user interactions within certain components. Process Overview The initial default setting for the J ...

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

Simple yet perplexing JavaScript within an Angular directive

In the tutorial, the author explains that each element in the stars array contains an object with a 'filled' value, which is determined as true or false based on the scope.ratingValue received from the DOM. directive('fundooRating', fu ...

Rangy wants to know how to enlarge the selection by including the parent node

When selecting HTML content, there can be situations where only a part of the desired text is highlighted. In such cases, it becomes necessary to expand the selection to encompass the entire element containing the selected text. some te<b>xt here is ...

Can I use IntelliJ to navigate to the declaration within node modules while utilizing TypeScript community stubs?

When working in IntelliJ or WebStorm on a JavaScript project that utilizes TypeScript community stubs, you can enable the IDE to provide helpful Parameter info. This feature is accessed through Preferences | Languages & Frameworks | JavaScript | Librar ...

Tips for explaining the structure of a basic Just functor in TypeScript

I am embarking on my first attempt to create a simple interface in TypeScript, and I find myself questioning every step along the way. The core question that troubles me is: How can I best describe this straightforward Jest matcher extension? /** * @par ...

The function signature '(priority1: number, priority2: number) => number' cannot be assigned to the parameter type '(a: unknown, b: unknown) => number'

I encountered the following type error (TypeScript - 3.7.5). Error TS2345: Argument of type '(priority1: number, priority2: number) => number' is not assignable to parameter of type '(a: unknown, b: unknown) => number'. Typ ...

PHP error: User data failed to be transmitted

I'm currently working on a website for capturing still photos of students. However, I'm facing an issue when trying to transfer the collected data and upload the picture with the corresponding "ID" provided in the prompt. For some reason, the dat ...