Angular2 call a Component from a Service - javascript

I am trying to call a Method in my Component from a a Service. What is the proper way to do this? I have tried to use rxjs Subject to create an Observable, but I cannot get it to fire.
import {Subject} from 'rxjs/Subject';
export class MyService {
callComponent = function(value) {
let invokeEvent = new Subject();
invokeEvent.next({some:value})
}
}
and in my Component
export class MyComponent {
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe(value => console.log(value))
}
}

Here's the plunker: http://plnkr.co/edit/WKSurRJMXo5JZOPrwSP5?p=preview
Change your service like this
import {Subject} from 'rxjs/Subject';
#Injectable()
export class MyService {
invokeEvent:Subject<any> = new Subject();
callComponent(value) {
this.invokeEvent.next({some:value})
}
}
Don't forget to provide it in your component
#Component({
selector: 'my-component',
template: `
`,
providers: [MyService]
})
export class MyComponent {
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe(value => console.log(value));
setTimeout(()=>{
this._myService.callComponent(1);
},1000);
}
}
Also, If you want this service to be a global shared service; put(provide) it in your bootstrap(old) or ngModule so it will share the same singleton instance throughout your app.

you can define Observable in service so that you can subscribe to that Observable from component.
//service
import { Injectable, Inject } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class MyService {
private notify = new Subject<any>();
/**
* Observable string streams
*/
notifyObservable$ = this.notify.asObservable();
constructor(){}
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
callComponent(value){
this.notify.next({some:value});
}
}
//Component
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Subscription } from 'rxjs/Subscription';
import { MyService } from './my.service';
export class MyComponent {
private subscription: Subscription;
constructor( private _myService: MyService ){
}
ngOnInit() {
this.subscription = this._myService.notifyObservable$.subscribe((value) => {
console.log(value);
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}

import {Subject} from 'rxjs/Subject';
export class MyService {
private invokeEvent = new Subject();
invokeEvent$ = this.missionConfirmedSource.asObservable(); //<<< this is important to declare invokeEvent with asObservable();
callComponent = function(value) {
invokeEvent.next({some:value})
}
}
export class MyComponent {
constructor(private _myService: MyService) {
this._myService
.invokeEvent$ //<<< subscribe to invokeEvent$ to get the result
.subscribe(value => console.log(value))
}
}

Related

How do I push data from a Subject observable to an array in the component?

I am trying to push a message into an array that is already declared as a variable in the component. I am using a service and have created a subject observable to take data from one component and inject it into another component. When I try to push the data onto the array after subscribing to the variable, it's updated temporarily but when I open that component, the data is not pushed. The array updates when I console log from inside the subscribe method but it's reset once I open that component. I don't know what is the problem. This is the code:
Service.ts
import { Injectable } from '#angular/core';
import { User } from './user';
import { Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class SerService {
private message = new Subject<string>();
sourceMessage$ = this.message.asObservable();
constructor() { }
sendMessage(message: string) {
this.message.next(message);
}
}
Receiver component
import { Component, OnInit } from '#angular/core';
import { SerService } from '../ser.service';
import { User } from "../user";
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public messages = ['hi', 'hello', 'bye'];
constructor(private _service: Service) { }
ngOnInit() {
this._service.message$
.subscribe(
message => {
this.messages.push(message);
}
);
}
}
Sender Component
import { Component, OnInit } from '#angular/core';
import { SerService } from '../ser.service';
import { User } from '../user';
#Component({
selector: 'app-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent {
userModel = new User('', '', '', '', false);
constructor (private _service : SerService) {}
onSubmit(){
this._service.sendMessage(this.userModel.message);
}
}
I can't update the message array. How do I do this with minimal changes?
You can create a service to send data from one component to another by using BehaviourSubject
Service:
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable({
providedIn: 'root'
})
export class DataService {
private userDetails = new BehaviorSubject<any>('');
currentUserDetails = this.userDetails.asObservable();
constructor() { }
sendUserDetails(message){
this.userDetails.next(message)
}
}
Sender Component:
import { DataService } from '/services/data.service';
export class SignupComponent implements OnInit {
public userDetails;
constructor(private _dataService: DataService) {}
ngOnInit(){
userDetails = new User('', '', '', '', false);
this._dataService.sendUserDetails(this.userDetails);
}
}
Receiver Component
import { DataService } from '/services/data.service';
export class LoginComponent implements OnInit {
public userDetails;
constructor(private _dataService: DataService) {}
ngOnInit(): void {
this._dataService.currentUserDetails.subscribe(userDetails => this.userDetails = userDetails);
}
Blockquote

Trigger function with event emitter

Is it possible to trigger a function in another component from the current component with EventEmitter, as sort of a callback? For example, after I finish the API request a success function occurs, like so:
#Output() afterAPIRequest = new EventEmitter();
handleSuccess() {
this.afterAPIRequest.emit();
}
Now, can I catch that somehow in another component and trigger another function, something like this?
// when emitted, run this
refreshListIfEmitted() {
this.refreshMyList();
}
use a service
import { Injectable } from '#angular/core';
import { Observable, Subject } from 'rxjs';
#Injectable()
export class MessageService {
private _message: Subject<any>;
constructor() {
this._message = new Subject();
}
get changes(): Observable<any> {
return this._message.asObservable();
}
set message(message: any) {
this._message.next(message);
}
}
component one
import { Component } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.scss'],
})
export class OneComponent {
constructor(private _http: HttpClient, private _message: MessageService) { }
apiRequest(): void {
this._http.get('end-point').subscribe(value => this._message.message = value);
}
}
component two
import { Component } from '#angular/core';
#Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.scss'],
})
export class TwoComponent {
constructor(private _message: MessageService) {
this._message.changes.subscribe(value => console.log(value));
}
}

Angular returns undefined

I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
restaurant.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { AuthService } from './auth.service'
#Injectable({
providedIn: 'root'
})
export class RestaurantService {
private restaurantUrl = 'https://dm.dnevnimeni.com/dmnew/podacirestorana.php';
public restaurant: Restaurant;
public loggedRestaurant: LoggedRestaurant
public restaurantID = this.authService.currRestaurant[0].id
constructor(private http: HttpClient, private authService: AuthService) { }
getRestaurant(ID): Observable<LoggedRestaurant> {
console.log('ID je' + this.restaurantID);
return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
}
}
informacije.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID = this.authService.currRestaurant[0].id;;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant();
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}
Update
Your code should be like this
Since you just need to get data you dont have to use post
so you can change from this
return this.http.post<LoggedRestaurant>(this.restaurantUrl, this.restaurantID);
to this
return this.http.get<LoggedRestaurant>(`${this.restaurantUrl}/${this.restaurantID}`);
and add in ngOnInit
ngOnInit() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
// do something else
});
Because your getRestaurant() method is not called in ngOnInit life cycle hook so the data is not avaibled
You have a few issues with your code. First, you never actually call the getRestaurant() function, thus the service call will never be requested.
Second, you're dealing with asynchronous code and can't expect the service call to be complete before the console.log(this.loggedRestaurant) is run.
My suggestion is that you change your function to return an Observable<LoggedRestaurant> and subscribe to that.
getRestaurant(): Observable<LoggedRestaurant> {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
Then you can use it as
ngOnInit() {
this.getRestaurant().subscribe(loggedRestaurant => {
console.log(loggedRestaurant);
});
}
Try this:
informacije.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
#Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
this.restaurantService.getRestaurant().subscribe(data => {
this.loggedRestaurant = data;
});
}
ngOnInit() {
this.getRestaurant(); // add this line
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}

Angular 5 BehaviorSubject not working for boolean value

I am trying to practice behaviorsubject in angular 5. I am written a small app with two components and want to change the value in both of them at once but the value is not changing. BehaviorSubject should change the value in all the components. Please help me understand.
Service
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class TestserviceService {
public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();
constructor() { }
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
}
Component One
import { Component, OnInit } from '#angular/core';
import{ TestserviceService } from '../../testservice.service';
#Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.css']
})
export class OneComponent implements OnInit {
isAdmin: boolean;
constructor(private testservice: TestserviceService) { }
ngOnInit() {
this.testservice.cast.subscribe(data => this.isAdmin = data);
}
changeValue(){
this.testservice.changeAdmin();
console.log(this.isAdmin);
}
}
Component One html
<button (click)="changeValue()">Click Me</button>
<p>
one {{isAdmin}}
</p>
Component Two
import { Component, OnInit } from '#angular/core';
import { TestserviceService } from '../../testservice.service';
#Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.css']
})
export class TwoComponent implements OnInit {
isAdmin: boolean;
constructor(private testservice: TestserviceService) { }
ngOnInit() {
this.testservice.cast.subscribe(data => this.isAdmin = data);
console.log("two "+this.isAdmin);
}
}
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
Should be
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
this.isAdmin is a BehaviorSubject and you were trying to set !thisAdmin which evaluates to false
Stackblitz
Change your service to :
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class SharedServiceService {
constructor() { }
public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
}
It should be this.isAdmin.value because this.admin will only be behaviourSubject's object
Live Demo

Passing value between two angular2 component typescript files

I have two components that are not parent and child components but i need to pass value from component A to component B.
example:
src/abc/cde/uij/componentA.ts has variable CustomerId = "ssss"
need to pas that variable customerID to src/abc/xyz/componentB.ts
Simple example:
Component A:
#Component({})
export class ComponentA {
constructor(private sharedService : SharedService) {}
sendMessage(msg : string) {
this.sharedService.send(msg);
}
}
Component B:
#Component({})
export class ComponentB {
constructor(private sharedService : SharedService) {
this.sharedService.stream$.subscribe(this.receiveMessage.bind(this));
}
receiveMessage(msg : string) {
console.log(msg); // your message from component A
}
}
Shared service:
#Injectable()
export class SharedService {
private _stream$ = new Rx.BehaviorSubject("");
public stream$ = this._stream$.asObservable();
send(msg : string) {
this._stream$.next(msg);
}
}
Shared service have to be placed in the same NgModule.
On your service define a setMyProperty() and a getMyProperty(). Then setMyProperty with a value from Component A. ComponentB then getMyProperty where you return the value...
You have to inject the service into both components.
You could give this a shot. Its pretty simple and straight forward.
I just followed THIS example and made some changes so that it could be siblings talking instead of parent/child.
my-service.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class MyService {
// Observable string sources
private myAnnouncedSource = new Subject<string>();
// Observable string streams
myAnnounced$ = this.myAnnouncedSource.asObservable();
// Service message commands
announceItem(item: string) {
this.myAnnouncedSource.next(item);
}
}
my-comp1.component.ts
import { Component } from '#angular/core';
import { MyService } from './my-service.service';
#Component({
selector: 'my-compA',
template: `...`,
providers: [MyService]
})
export class MyComponentA {
constructor(private myService: MyService) {
}
announceToOtherComps() {
let sharedItem = "shibby";
this.myService.announceItem(sharedItem);
}
}
my-comp2.component.ts
import { Component, Input, OnDestroy } from '#angular/core';
import { MyService } from './my-service.service';
import { Subscription } from 'rxjs/Subscription';
#Component({
selector: 'my-compB',
template: `...`,
providers: [MyService]
})
export class MyComponentB implements OnDestroy {
sharedItem = '<no data>';
subscription: Subscription;
constructor(private myService: MyService) {
this.subscription = myService.myAnnounced$.subscribe(
item => {
this.sharedItem = item;
});
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
<component-a [id]="product.id"></component-a>
In the component-a ts file .Use it like below
export class ComponentA implements OnInit {
#Input() // <------------
id: number;
(...)
}

Categories