2

I am trying to use a service to define a shared resource client between several views. I first select the client from an index and set it:

itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => { 
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();


  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}

Then I try to get the client that was just set and subscribe to it so that I can detect changes to client in this view and its siblings:

this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)

but this call to getClient() never returns an error or anything at all. What am I doing wrong with my observable?

EDIT: Here is the component:

@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams, 
    private filterObject: FilterObject, 
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}
9
  • Where do you provide the service? Commented Jun 5, 2017 at 15:34
  • in the component where I am trying to display the data. The same component where this.clientService.getClient() is called Commented Jun 5, 2017 at 15:36
  • 1
    What is this supposed to do? val => this.client = val Commented Jun 5, 2017 at 15:37
  • I thought it would take the data returned from getClient() and set it to this.client Commented Jun 5, 2017 at 15:41
  • I also added changed the line () => {} to () => { console.log("completed") } and never see that in the console Commented Jun 5, 2017 at 15:43

2 Answers 2

3

why are you defining ClientService in the component class. is ClientService related single component ?

you need provide ClientService in the app.module.ts and inject clientservice in the component class. if you provide clientservice in the component it will create different instance for the component

app.module.ts

 providers: [ ClientService  ],

ClientDetailsPage.ts remove providers: [ ClientService ]

{
constructor(clientService  : ClientService  ) { 

  }
}
Sign up to request clarification or add additional context in comments.

8 Comments

I didn't realize I shouldn't have it there. Removing it didn't solve the problem though.
can you create plunker.
I've tried and can't get it working. Can you provide a link with a plunker that uses services?
fixed couple of issues. working plnkr plnkr.co/edit/OCaUBgnGj6AenWyeWLxA?p=preview important points 1) remove client service provider from home component(try to read dependency injection) 2) used behavior subject instead of subject. Next time onward explain question clearly and it took me lot of time understand your question and plunker. one more thing is your plunker no match to your question (there is no getClient function itself in plunker)
|
0

You can try using BehaviorSubject instead of Subject, the unique change it you need provide a default value. Same error I fixed with that, but with no problem found.

Comments

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.