Reputation: 4508
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 ?
Upvotes: 1
Views: 571
Reputation: 22203
You need to subscribe
the http call
Try like this:
ngOnInit() {
this.testService.getObject(this.testID).subscribe((data:test1Model) => {
this.testObjVariable = data
});
}
Upvotes: 1
Reputation: 361
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.
Upvotes: 0