How to make from two services one service? - javascript

I have a angular 8 application and a service, like this:
export class ProfileUserService {
user$ = this.authService.loginStatus().pipe(take(1));
constructor(private profileService: ProfileService, private authService: AuthService) {}
getProfile(): Observable<ProfileApi> {
return this.user$.pipe(mergeMap(({ profile }) => this.profileService.get(profile.participant)));
}
}
And I have a component where I use the service where I call the method, like this:
export class SettingsAccountComponent extends FormCanDeactivate implements OnInit, OnDestroy {
constructor(
private profileUserService: ProfileUserService){}
ngOnInit() {
this.innerWidth = window.innerWidth;
this.profileSubscription = this.profileUserService.getProfile().subscribe((profile: ProfileApi) => {
this.profile = profile;
this.deletePicture = false;
this.buildForm();
});
}
}
But I want to call directly in the component SettingsAccountComponent : this service:
private profileService: ProfileService
But the problem is this:
user$ = this.authService.loginStatus().pipe(take(1));
Because I need that for getting the participantId. But so my question is, how to combine the ProfileService, like this
this.profileSubscription = this.profileService.get().subscribe((profile: ProfileApi) => {
this.profile = profile;
this.deletePicture = false;
this.buildForm();
});
witht the:
user$ = this.authService.loginStatus().pipe(take(1));
because now in the get() method it expecs a ParticipantId
So what I have to change?
Thank you

I think a switchMap can help you.
Try:
import { switchMap } from 'rxjs/operators';
...
this.profileSubscription = this.profileService.user$.pipe(
switchMap(({ profile }) => this.profileService.get(profile.participant))
).subscribe((profile: profileAPI) => {
this.profile = profile;
this.deletePicture = false;
this.buildForm();
});
I see you've already done mergeMap in your service, switchMap is very similar.

Related

Unable to pass data between two components using services

I want to pass the array value from Search component to History component to display the history of the searches done.
I have written the code in this manner -
search-page.component.ts
export class SearchPageComponent implements OnInit {
constructor( private dataService :DataService) { }
githubSearch(username:any){
return new Promise((resolve, reject) => {
this.httpClient.get("----")
.pipe(map(Response => Response))
.subscribe((res: any) => {
this.searchResultObject = res;
this.allSearchResultArray.push(this.searchResultObject);
this.dataService.changeParam(this.allSearchResultArray)
resolve(this.searchResultObject );
});
});
}
passDataToService(){
this.dataService.allPassedData.next(this.allSearchResultArray);
}
}
data.service.ts
export class DataService {
allPassedData: any
constructor() { }
storePassedObject(passedData:any){
this.allPassedData.next(passedData);
}
retrievePassedObject(){
return this.allPassedData;
}
}
history-page.component.ts
export class HistoryPageComponent implements OnInit {
historyData : any = [];
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.historyData = this.dataService.retrievePassedObject()
}
}
I am unable to retrieve data via this designed code.
First create subject in service and make it as observable
data.service.ts
export class DataService {
private allPassedData = new Subject<any>();
allPassedData$ = this.allPassedData.asObservable();
constructor() { }
setPassedData(retrievedData: any) {
this.allPassedData.next(retrievedData);
}
}
Now set the data in the observable
search-page.component.ts
passDataToService() {
this.dataService.setPassedData(this.allSearchResultArray);
}
history-page.component.ts
ngOnInit(): void {
// for retrieval of data in history component
this.dataService.allPassedData$.subscribe((data) => {
this.historyData = data
})
}

How to Return a Observable value if its not null otherwise call an http service and return the data?

#Injectable()
/***
* Service for manage profile
*/
export class ManageProfileService {
private UserDetails: any = null;
public GetUserDetails$: Observable<any>
}
I want to subscribe the GetUserDetails Observable from the service and it should return if the value of UserDetails is not null then return the UserDetails variable value otherwise call an HTTP service "getUserDetails" and return the data what gets from the service, if HTTP service if failed it should return null. please any help to resolve.
You could use the RxJS of function to return the variable UserDetails as an observable.
Try the following
Service
import { of } from 'rxjs';
#Injectable()
export class ManageProfileService {
private UserDetails: any = null;
public getUserDetails(): Observable<any> {
return (!!this.UserDetails) ? of(this.UserDetails) : this.http.get('url');
}
}
You could then subscribe in the component
Component
export class SomeComponent implements OnInit {
...
ngOnInit() {
this.manageProfileService.getUserDetails().subscribe(
res => {
// res - `this.manageProfileService.UserDetails` if it's defined
// res - response from `http.get('url')` if not
},
err => { }
);
}
}

Have realtime updates for a single Firestore document

There is a lot of documentation and examples of firestore collections getting realtime updates. However, there is very little for those who wish to have a single document have real time updates. I want to have a single document (an item), on a page where only the item will be viewed and manipulated and any changes to document, will have realtime updating.
Here is my component that wants to do stuff with the item:
import { Component, OnInit } from '#angular/core';
import { ItemsService } from '../shared/items.service';
import { ActivatedRoute, Router } from '#angular/router';
#Component({
selector: 'app-view-item',
templateUrl: './view-item.component.html',
styleUrls: ['./view-item.component.css']
})
export class ViewItem implements OnInit {
item;
private sub: any;
constructor(
// Service used for Firebase calls
private itemsService: ItemsService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
// Item retrieved from */item/:id url
this.sub = this.route.params.subscribe(params => {
this.getItem(params['id']);
});
}
getItem = (id) => {
this.itemsService.getItem(id).subscribe(res => {
console.log(res);
this.item = res;
console.log(this.item);
});
}
And the service it uses for calls:
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreDocument } from '#angular/fire/firestore';
#Injectable({
providedIn: 'root'
})
export class ItemsService {
constructor(
private firestore: AngularFirestore
)
getItem(id) {
return this.firestore.collection('items').doc(id).snapshotChanges();
}
}
The log I get for console.log(this.item) is undefined. Calling this.item in the console returns the same. I am unsure of how to proceed and would appreciate any guidance. Logging res in the console returns a byzantine object. Perhaps that's how I access the item, but if so, why is it not saved in this.item and how do I access the item's values?
snapshotChanges returns an observable of actions, not the actual value.
You should extract the value with action.payload.doc.data():
So your code should look like the following example.
getItem(id) {
return this.firestore.collection('items').doc(id).snapshotChanges()
.pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
})
);
}
Or you can use valueChanges of doc.
getItem(id) {
return this.firestore.collection('items').doc(id).valueChanges();
}

Angular 2: get data from http in parent-component and subscribe on it nested

I plan to do such architecture:
component store
-- nested-component book
in store - i have an service call, which get data from service, and i do a subscription on result. Like it was described in angular2 docs (http).
And i want to use this data in nested components: in forms (formBuilder), in material-design elements etc.
Which way is the best, to do this? I'm new to angular2.
Store:
book: IBook;
constructor(private bookService: BookService) { }
ngOnInit() {
this.bookService.getBook('1')
.subscribe((book) => {
this.book = book;
});
}
BookService:
...
getBook (id): Observable<IBook> {
return this.http.get(this.url + '/' + id)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
...
Book:
#Input() book:IBook;
constructor() {}
ngOnInit() {
/*How here can i subscribe on book http data get?, so that i can use async value in forms etc?*/
});
Because, if i use async book everywhere (not formBuilder) - all is ok, but formBuilder is in need to update values, after data is loaded in parent component. How can i do this?
What about passing the bookID to the BookComponent and letting the BookComponent handle the async http get in ngInit?
export class Book implements OnInit {
#Input() bookID: number;
private book: IBook;
constructor(private bookService: BookService) {}
ngOnInit() {
this.bookService.getBook(this.bookID)
.subscribe((book) => {
this.book = book;
});
}
}
Otherwise you have a few options which are explained in https://angular.io/docs/ts/latest/cookbook/component-communication.html
I'll briefly highlight two ways which I think you could use.
Intercept input property changes with ngOnChanges
export class Book implements OnChanges {
#Input() book: IBook;
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
for (let propName in changes) {
// handle updates to book
}
}
}
more info https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
Parent and children communicate via a service
#Injectable()
export class BookService {
books = new Subject<IBook>();
getBook(id): Observable<IBook> {
return this.http.get(this.url + '/' + id)
.map(d => {
let book = this.extractData(d);
this.books.next(book);
return book;
})
.catch(this.handleError);
}
...
}
#Component({
selector: 'book',
providers: []
})
export class Book implements OnDestroy {
book: IBook
subscription: Subscription;
constructor(private bookService: BookService) {
this.subscription = bookService.books.subscribe(
book => {
this.book = book;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
#Component({
selector: 'store',
providers: [BookService]
})
export class Store {
book: IBook;
constructor(private bookService: BookService) { }
ngOnInit() {
this.bookService.getBook('1')
.subscribe((book) => {
this.book = book;
});
}
}

Angular 2 access parent routeparams from child component [duplicate]

How do I get the RouteParams from a parent component?
App.ts:
#Component({
...
})
#RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/:username/...', component: ParentComponent, as: 'Parent'}
])
export class HomeComponent {
...
}
And then, in the ParentComponent, I can easily get my username param and set the child routes.
Parent.ts:
#Component({
...
})
#RouteConfig([
{ path: '/child-1', component: ChildOneComponent, as: 'ChildOne' },
{ path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' }
])
export class ParentComponent {
public username: string;
constructor(
public params: RouteParams
) {
this.username = params.get('username');
}
...
}
But then, how can I get this same 'username' parameter in those child components? Doing the same trick as above, doesn't do it. Because those params are defined at the ProfileComponent or something??
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(
public params: RouteParams
) {
this.username = params.get('username');
// returns null
}
...
}
UPDATE:
Now that Angular2 final was officially released, the correct way to do this is the following:
export class ChildComponent {
private sub: any;
private parentRouteId: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.parent.params.subscribe(params => {
this.parentRouteId = +params["id"];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
ORIGINAL:
Here is how i did it using the "#angular/router": "3.0.0-alpha.6" package:
export class ChildComponent {
private sub: any;
private parentRouteId: number;
constructor(
private router: Router,
private route: ActivatedRoute) {
}
ngOnInit() {
this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
this.parentRouteId = +params["id"];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
In this example the route has the following format: /parent/:id/child/:childid
export const routes: RouterConfig = [
{
path: '/parent/:id',
component: ParentComponent,
children: [
{ path: '/child/:childid', component: ChildComponent }]
}
];
You shouldn't try to use RouteParams in your ChildOneComponent.
Use RouteRegistry, instead!
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(registry: RouteRegistry, location: Location) {
route_registry.recognize(location.path(), []).then((instruction) => {
console.log(instruction.component.params['username']);
})
}
...
}
UPDATE: As from this pull request (angular beta.9): https://github.com/angular/angular/pull/7163
You can now access to the current instruction without recognize(location.path(), []).
Example:
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(_router: Router) {
let instruction = _router.currentInstruction();
this.username = instruction.component.params['username'];
}
...
}
I haven't tried it, yet
Further details here:
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta9-2016-03-09
https://angular.io/docs/ts/latest/api/router/Router-class.html
UPDATE 2:
A small change as from angular 2.0.0.beta15:
Now currentInstruction is not a function anymore. Moreover, you have to load the root router. (thanks to #Lxrd-AJ for reporting)
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(_router: Router) {
let instruction = _router.root.currentInstruction;
this.username = instruction.component.params['username'];
}
...
}
As mentioned by Günter Zöchbauer, I used the comment at https://github.com/angular/angular/issues/6204#issuecomment-173273143 to address my problem. I used the Injector class from angular2/core to fetch the routeparams of the parent. Turns out angular 2 does not handle deeply nested routes. Maybe they'll add that in the future.
constructor(private _issueService: IssueService,
private _injector: Injector) {}
getIssues() {
let id = this._injector.parent.parent.get(RouteParams).get('id');
this._issueService.getIssues(id).then(issues => this.issues = issues);
}
I found an ugly but working solution, by requesting the parent (precisely the 2nd ancestor) injector, and by getting the RouteParams from here.
Something like
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(injector: Injector) {
let params = injector.parent.parent.get(RouteParams);
this.username = params.get('username');
}
}
RC5 + #angular/router": "3.0.0-rc.1 SOLUTION: It seems that this.router.routerState.queryParams has been deprecated. You can get the parent route params this way:
constructor(private activatedRoute: ActivatedRoute) {
}
this.activatedRoute.parent.params.subscribe(
(param: any) => {
let userId = param['userId'];
console.log(userId);
});
You can take component of parent route inside of child component from injector and then get any from child component. In you case like this
#Component({
...
})
export class ChildOneComponent {
public username: string;
constructor(
public params: RouteParams
private _injector: Injector
) {
var parentComponent = this._injector.get(ParentComponent)
this.username = parentComponent.username;
//or
this.username = parentComponent.params.get('username');
}
...
}
Passing Injector instance to constructor in child component may not be good if you want to write unit tests for your code.
The easiest way to work around this is to have a service class in the parent component, in which you save your required params.
#Component({
template: `<div><router-outlet></router-outlet></div>`,
directives: [RouterOutlet],
providers: [SomeServiceClass]
})
#RouteConfig([
{path: "/", name: "IssueList", component: IssueListComponent, useAsDefault: true}
])
class IssueMountComponent {
constructor(routeParams: RouteParams, someService: SomeServiceClass) {
someService.id = routeParams.get('id');
}
}
Then you just inject the same service to child components and access the params.
#Component({
template: `some template here`
})
class IssueListComponent implements OnInit {
issues: Issue[];
constructor(private someService: SomeServiceClass) {}
getIssues() {
let id = this.someService.id;
// do your magic here
}
ngOnInit() {
this.getIssues();
}
}
Note that you should scope such service to your parent component and its child components using "providers" in parent component decorator.
I recommend this article about DI and scopes in Angular 2: http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html
In RC6, router 3.0.0-rc.2 (probably works in RC5 as well), you can take route params from the URL as a snapshot in case that params won't change, without observables with this one liner:
this.route.snapshot.parent.params['username'];
Don't forget to inject ActivatedRoute as follows:
constructor(private route: ActivatedRoute) {};
With RxJS's Observable.combineLatest, we can get something close to the idiomatic params handling:
import 'rxjs/add/operator/combineLatest';
import {Component} from '#angular/core';
import {ActivatedRoute, Params} from '#angular/router';
import {Observable} from 'rxjs/Observable';
#Component({ /* ... */ })
export class SomeChildComponent {
email: string;
id: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
Observable.combineLatest(this.route.params, this.route.parent.params)
.forEach((params: Params[]) => {
this.id = params[0]['id'];
this.email = params[1]['email'];
});
}
}
I ended up writing this kind of hack for Angular 2 rc.1
import { Router } from '#angular/router-deprecated';
import * as _ from 'lodash';
interface ParameterObject {
[key: string]: any[];
};
/**
* Traverse route.parent links until root router and check each level
* currentInstruction and group parameters to single object.
*
* e.g.
* {
* id: [314, 593],
* otherParam: [9]
* }
*/
export default function mergeRouteParams(router: Router): ParameterObject {
let mergedParameters: ParameterObject = {};
while (router) {
let currentInstruction = router.currentInstruction;
if (currentInstruction) {
let currentParams = currentInstruction.component.params;
_.each(currentParams, (value, key) => {
let valuesForKey = mergedParameters[key] || [];
valuesForKey.unshift(value);
mergedParameters[key] = valuesForKey;
});
}
router = router.parent;
}
return mergedParameters;
}
Now in view I collect parameters in view instead of reading RouteParams I just get them through router:
#Component({
...
})
export class ChildishComponent {
constructor(router: Router) {
let allParams = mergeRouteParams(router);
let parentRouteId = allParams['id'][0];
let childRouteId = allParams['id'][1];
let otherRandomParam = allParams.otherRandomParam[0];
}
...
}
In FINAL with little help of RXJS you can combine both maps (from child and parent):
(route) => Observable
.zip(route.params, route.parent.params)
.map(data => Object.assign({}, data[0], data[1]))
Other questions one might have:
Is it really a good idea to use above - because of coupling (couple child component with parent's param's - not on api level - hidden coupling),
Is it proper approach in term of RXJS (it would require hardcore RXJS user feedback ;)
You can do it on the snapshot with the following, but if it changes, your id property will not be updated.
This example also shows how you can subscribe to all ancestor parameter changes and look for the one you are interested in by merging all of the parameter observables. However, be careful with this method because there could be multiple ancestors that have the same parameter key/name.
import { Component } from '#angular/core';
import { ActivatedRoute, Params, ActivatedRouteSnapshot } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/merge';
// This traverses the route, following ancestors, looking for the parameter.
function getParam(route: ActivatedRouteSnapshot, key: string): any {
if (route != null) {
let param = route.params[key];
if (param === undefined) {
return getParam(route.parent, key);
} else {
return param;
}
} else {
return undefined;
}
}
#Component({ /* ... */ })
export class SomeChildComponent {
id: string;
private _parameterSubscription: Subscription;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
// There is no need to do this if you subscribe to parameter changes like below.
this.id = getParam(this.route.snapshot, 'id');
let paramObservables: Observable<Params>[] =
this.route.pathFromRoot.map(route => route.params);
this._parametersSubscription =
Observable.merge(...paramObservables).subscribe((params: Params) => {
if ('id' in params) {
// If there are ancestor routes that have used
// the same parameter name, they will conflict!
this.id = params['id'];
}
});
}
ngOnDestroy() {
this._parameterSubscription.unsubscribe();
}
}
Getting RouteParams from parent component in Angular 8 -
I have a route http://localhost:4200/partner/student-profile/1234/info
Parent route - student-profile
Param - 1234 (student_id)
Child route - info
Accessing param in child route (info) -
Import
import { ActivatedRoute, Router, ParamMap } from '#angular/router';
Constructor
constructor(private activatedRoute: ActivatedRoute, private router: Router) { }
Accessing parent route params
this.activatedRoute.parent.paramMap.subscribe((params: ParamMap) => this.studentId = (params.get('student_id')));
Now, our variable studentId has the param value.

Categories