1

I have c# class test1

public class test1
    {
        public int testID{ get; set; }
        public string testName{ get; set; }
        public int testValue{ get; set; }
}

In Angular I have testService which has function getObject

  getObject(param) {    
      return this.http.post(appSettings.BackEndUrl + '/getObject?testID='+param,'');     
    }

In Angular I also made same type class

export class test1Model{
    testID: Number;
    testName: String;
    testValue: Number;
}

Now In some component I want to create variable

testObjVariable: test1Model;

And put that api data inside it. I'm trying to do it this way

  ngOnInit() {
    this.testObjVariable = this.testService.getObject(this.testID);
  }

And I get error

Type 'Observable' is missing the following properties from type 'test1Model': testID, testName, testValue

Despite the fact that teoretically I'm transfering just exactly those type of data. What am I doing wrong ?

2 Answers 2

1

You need to subscribe the http call

Try like this:

ngOnInit() { 

  this.testService.getObject(this.testID).subscribe((data:test1Model) => {
   this.testObjVariable = data
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

That added new error The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? After some thinking I've tryied to declare testObjVariable as any. In that case errors gone, but when I test application I get Cannot read property 'testName' of undefined
@david Refer to this Solution stackoverflow.com/a/58748009/6412916
@David Just add data:test1Model
0

I agree with @Adrita Sharma solution but in order to get rid of that error, You may need to add return type to your typescript function like this:

Solution#1:

getObject(param) : Observable<test1Model> {    
  return this.http.post(appSettings.BackEndUrl + '/getObject?testID='+param,'');     
}

or

getObject(param) {    
  return this.http.post<test1Model>(appSettings.BackEndUrl + '/getObject?testID='+param,'');     
}

Solution#2: you can have something like this where you are assigning to variable

   ngOnInit() {
      this.testService.getObject(this.testID).subscribe((data: test1Model) => {
        this.testObjVariable = data
      });
   }

because by default typescript function is returning Observable<test1Model> object, that is not assignable to test1Model type. I hope this make sense to you.

1 Comment

none of the above helps :( when I try to console.log I get "undefined". At the same time from the c# log I see that data is going...

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.