Joe Keene
Joe Keene

Reputation: 2351

How do I make a service function that takes a value and returns an observable in Angular 2?

My Service:-

    @Injectable()
    export class MyService {

        doStuff(value){
             //Do stuff and when done return new data

             return newData;
        }

    }

My Component:-

    export class MyComponent implements OnInit {
        constructor(private _myService: MyService){}

        ngOnInit() {
            this._myService.doStuff(value)
            .subscribe((data) => {
                console.log("new data: ", data);
            })
        }
    }

So my question is, how do I make the doStuff() function return an observable. Also I want to subscribe to said function whilst passing a value to it. How do I do this please?

I have it working where by I set a variable as a new Subject() (inside my service) - then I call .next() on said variable and pass the value back. Only issue is I have to call my doStuff() function and then subscribe to the variable something like the below :-

My current Service:-

    @Injectable()
    export class MyService {
        myData:any = new Subject<any>();
        myDataAnnounce = this.myData.asObservable();

        doStuff(value){
             //Do stuff and when done return new data
             this.myData.next(newData);
        }

    }

My current Component:-

    export class MyComponent implement OnInit {
        constructor(private _myService: MyService){}

        ngOnInit() {
            this._myService.doStuff(value);
            this._myService.myDataAnnounce
            .subscribe((data) => {
                console.log("new data: ", data);
            })
        }


    }

I would like to make one call with the value I want to pass and then subscribe. Thanks in advance for any help you can provide.

Upvotes: 0

Views: 1681

Answers (1)

Alexander Leonov
Alexander Leonov

Reputation: 4794

This is pretty simple. As @jonrsharpe said you just need to return some observable. Sometimes I use the same approach for debugging or as a development quick start if I want to start some work with no real service in place.

@Injectable()
export class MyService {
    doStuff(value) {
         // When calling to real service is implemented 
         // you can just replace this with something like 
         //    return this.http.get(...).map(r => r.json());
         // If json response has the same structure as newData then 
         // your MyComponent will not even notice that something has changed.
         return Observable.of(newData);
    }
}

export class MyComponent implement OnInit {
    constructor(private _myService: MyService){}

    ngOnInit() {
        this._myService.doStuff(value).subscribe((data) => {
            console.log("new data: ", data);
        });
    }
}

Upvotes: 1

Related Questions