I'm attempting to pass data from a directive to a component via a service. The return from my transfer service file says that the type 'Transfer' is not assignable to Observer . I also get ' Property 'subscribe' does not exist on type '() => Observable ' in my component file when trying to subscribe to the service. Why is this and how can I fix it? my files are
transfer.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Transfer } from './transfer';
@Injectable()
export class TransferService {
constructor(private transfer: Transfer){}
private pageData;
private contentData;
private contentBox;
setData(pData, cData, bData){
this.pageData = pData;
this.contentData = cData;
this.contentBox = bData;
}
getData(): Observable<Transfer>{
this.transfer.page = this.pageData;
this.transfer.content = this.contentData;
this.transfer.contentBox = this.contentBox;
this.clearData();
return this.transfer;
}
clearData(){
this.pageData = undefined;
this.contentData = undefined;
this.contentBox = undefined;
}
}
transfer.ts
import { ElementRef } from '@angular/core';
export interface Transfer{
page: [
{
pageNum: number,
subStart: number,
subEnd: number
}
];
content: string;
contentBox: ElementRef;
}
article.component.ts - component
transfer(){
this.ts.getData.subscribe(data => this.tsData = data);
}
paginator.ts - directive
// Pass date via transferservice.ts
transfer(){
this.ts.setData(this.pageJump, this.content, this.contentBox);
}
EDIT: using @ritaj's solution resolved the issue of not being assignable/property not existing, but now I'm getting ' Error: Can't resolve all parameters for TransferService '
STACKBLITZ EDIT: https://stackblitz.com/edit/mesh
Your getData()
service method does NOT return Observable, as you have type
d.
It just returns a normal JS object, which does not have .subscribe() method, obviously.
Change your article.component.ts
transfer()
method to this:
transfer(){
this.tsData = this.ts.getData();
}
And change getData signature to:
getData(): Transfer {}
constructor(public ts : TransferService){}
transfer(){
this.tsData = this.ts.getData(); // directly call
}
providers:[TransferService]
Here is Stackblitz link, just a demo to reflect solution to the problem:-
https://stackblitz.com/edit/angular5-service-example-onwtg6?file=app/article.component.ts
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.