Angular 7 - Get Param Value from the url - angular7

I already went through link: How to get param from url in angular 4? and trying to follow the same approach.
I am using Angular 7 and my current URL: http://localhost:4200/student-details/488
When I clicked on different Side Pane link, I want to get the value 488 and pass that value to other component.
I used below in ngOnit() where my page is routing to.
this.route.paramMap.subscribe(params => {
console.log('params', params);
});

Assuming your routing module has something similar to below -
{
path: 'student-details/:id',
component: StudentDetailsComponent,
}
You can get the 488 (:id) property from student-details/488 like -
this.route.paramMap.subscribe(params => {
let id = params.get('id');
// let id = +params.get('id'); //<--- if you want to convert it into a numeric value
console.log('Student Id', id);
});

I am using angular 8
Component from where I am routing
this.router.navigate(['/ledger-card'], { queryParams: { branchId: '10', loanAcc: '2738'}});
Component where I am receiving the routed data
const param = this.route.snapshot.queryParamMap;
if (param.get('branchId')) {
const branchId = param.get('branchId');
const loanAcc = param.get('loanAcc');
}
** Make sure you import ActivatedRoute
import { ActivatedRoute } from '#angular/router';
constructor(private route: ActivatedRoute) {}

Routing Module:
...
{
path: '',
component: YourListComponent
},
{ //
path: ':id', // <--
component: YourSingleComponent // <--
} //
...
yoursingle.component.ts
...
import { ActivatedRoute } from '#angular/router';
...
export class YourSingleComponent implements OnInit {
...
singleID: number;
...
constructor(
private _route: ActivatedRoute,
) {
}
ngOnInit() {
this.singleID = parseInt(this._route.snapshot.paramMap.get("id"));
}
...
}

Related

How to fix subscribe not exist in type void

I am new to angular 7 and didn't find any proper answer for similar questions posted.
I am getting Property 'subscribe' does not exist on type 'void' in angular-cli. I tried importing subscribe from rxjs but didn't find that library.
The problem is in the UpdateRecord Function!
product.component.ts code:
the code bellow is exist in compoent.ts of product
import { Component, OnInit } from '#angular/core';
import { ProductService } from 'src/app/shared/product.service';
import { NgForm } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { filter, map } from 'rxjs/operators';
#Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
constructor(private service : ProductService, private toastr : ToastrService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form?: NgForm) {
if (form != null)
form.resetForm();
this.service.formData = {
ProductID: null,
ProductName: '',
ProductDescription: '',
Price: 0.00,
Image: '',
Qte: null
}
}
onSubmit(form: NgForm) {
if (form.value.ProductID == null)
this.insertRecord(form);
else
this.updateRecord(form);
}
insertRecord(form: NgForm) {
this.service.postProduct(form.value).subscribe(res => {
this.toastr.success('Inserted successfully', 'Product. Register');
this.resetForm(form);
this.service.refreshList();
});
}
updateRecord(form: NgForm) {
this.service.putProduct(form.value).subscribe(res => {
this.toastr.success('Updated successfully', 'Product. Update');
this.resetForm(form);
this.service.refreshList();
});
}
}
product.service.ts code :
the code bellow is exist in service file related to product
import { Injectable } from '#angular/core';
import { Product } from './product.model';
import { HttpClient } from "#angular/common/http";
#Injectable({
providedIn: 'root'
})
export class ProductService {
formData : Product
list : Product[]
readonly rootURL= 'http://localhost:50369/api'
constructor(private http : HttpClient) { }
postProduct(formData : Product){
return this.http.post(this.rootURL+'/Product', formData);
}
refreshList(){
return this.http.get(this.rootURL+'/Product')
.toPromise().then(res => this.list = res as Product[]);
}
putProduct(formData : Product){
this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
}
Thanks in advance,
I missed return :
So in putProduct function in product.service.ts is updated to be :
putProduct(formData : Product){
return this.http.put(this.rootURL+'/Product/'+formData.ProductID,FormData);
}
And it's working now!
Your HttpClient.put function seems to be incorrectly used (you are passing the class as parameter when you should be passing the object).
Look for the function updateHero() in this StackBlitz example.
/** PUT: update the hero on the server. Returns the updated hero upon success. */
updateHero (hero: Hero): Observable<Hero> {
httpOptions.headers =
httpOptions.headers.set('Authorization', 'my-new-auth-token');
return this.http.put<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('updateHero', hero))
);
}

Angular 7 HttpClient POST - Bad request

Taking again the tutorial of the site Angular, I created in winamp a database with a table including a field {"id": id, "name": name} and I make 2 queries on this table with Symfony4:
1) A request to list heroes.
2) A request to create hero.
Executed from Angular 7, the query 1) works perfectly (route / listerHeroes).
Executed from Angular 7, query 2) does not work, it returns error 405 (route / ajouterHero). However launched from Postman, this query works.
I can not find any documentation to explain to me this bug on which I stumble for several days. A track please
Below copy of both classes: heroes.service.ts and component3.component.ts
// heroes.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { HttpErrorHandler, HandleError } from './http-error-handler.service';
import { Hero } from '../assets/Structure';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
#Injectable({ providedIn: 'root' })
export class HeroesService {
heroesUrl = 'http://heroes/';
private handleError: HandleError;
constructor(private http: HttpClient, httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('HeroesService');
}
getHeroes$(): Observable<Hero[]> {
return this.http.get<Hero[]>(`${this.heroesUrl}listerHeroes`, httpOptions);
}
addHero(hero: Hero): Observable<Hero> {
return this.http
.post<Hero>(`${this.heroesUrl}ajouterHero`, hero, httpOptions)
.pipe(catchError(this.handleError('addHero', hero)));
}
}
// component3.component.ts
import { Component, OnInit } from '#angular/core';
import { HeroesService } from '../heroes.service';
import { Hero } from '../../assets/Structure';
#Component({
selector: 'app-component3',
templateUrl: './component3.component.html',
styleUrls: ['./component3.component.css']
})
export class Component3Component implements OnInit {
heroes: Hero[];
editHero: Hero;
constructor(private heroesService: HeroesService) {}
ngOnInit() {
this.heroesService.getHeroes$().subscribe(res => (this.heroes = res));
}
addHero(name: string): void {
name = name.trim();
console.log('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF C3A name =', name);
if (!name) {
return;
}
const newHero: Hero = { 'id': 0, 'name': name } as Hero;
this.heroesService.addHero(newHero).subscribe(hero => {
console.log('GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG C3B hero= ', hero);
this.heroes.push(hero);
});
}
}
I found the solution:
The blocking was listed backend (Symfony4) which refused the pre-query OPTIONS. It was necessary to install and configure the bundle nelmio (https://github.com/nelmio/NelmioApiDocBundle) which allows the smooth running of the request.

Unable to get single property from response Angular 2

I want to access the property 'Status' from the controller and simply do some operations but I am unable to get this property and do any further operation. I am sharing my code below:
TasksController:
[HttpGet]
public ActionResult GetTasks()
{
var q = (from a in db.Tsk
join b in db.TType on a.TaskTypeID equals b.TaskTypeID
join c in db.Prior on a.PriorityID equals c.PriorityID
join d in db.Usr on a.AssignedTo equals d.Employees.EmpName
select new
{
a.TaskID,
a.TaskCode,
a.AssignedTo,
a.Date,
a.DueDate,
a.Status,
a.Reply,
a.PriorityID,
a.TaskTypeID,
b.TaskType,
c.Priorities,
d.Login
}).ToList().Skip(1).AsEnumerable();
db.Configuration.ProxyCreationEnabled = false;
return Json(q, JsonRequestBehavior.AllowGet);
}
AppService:
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import { Observable } from 'rxjs/Observable'
#Injectable()
export class AppService {
constructor(private _http: Http) { }
//Task Register
getFTRs(c: string) {
return this._http.get('Tasks/GetTasks').map(res => res.json().filter(a => a.Login === c));
}
}
HomeComponent:
import { Component, OnInit, Input } from '#angular/core';
import { AuthenticationService } from '../_services/index';
import { AppService } from '../app.service';
import { LoginComponent } from '../login/index';
import { User, TaskRegisters } from '../contract';
import { Message } from '../message';
#Component({
moduleId: module.id,
selector: 'home',
templateUrl: 'home.component.html',
providers: [LoginComponent]
})
export class HomeComponent implements OnInit {
users: User[];
tasks: string;
msgs: Message[] = [];
curr: any;
constructor(private userService: AuthenticationService,
private Tsk: AppService,
private Log: LoginComponent) { }
ngOnInit() {
debugger;
this.curr = localStorage.getItem('currentUser').slice(1);
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res.Status,
error => console.log(error)
});
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
}
}
Status is a boolean and if boolean is true, I want to push the message in msgs array. I am unable to get the value of Status and store it in tasks variable of home component. Whenever I run the program it shows this.tasks as undefined thus making and comparison impossible. Any help will be appreciated.
Change:
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res.Status,
error => console.log(error)
});
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
to
this.Tsk.getFTRs(this.curr).subscribe(
(res) => {
console.log(res); //What does this print?
this.tasks = res.Status;
console.log(this.tasks); //What does this print?
if (this.tasks) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
},
(error) => {console.log(error);}
);
Since you're assingning this.tasks inside getFRSs' callback which is async, by the time you are using it below in the if statement it is undefined.
Since this.tasks is available to me now after the edit of #echonax I did this to make it work!
ngOnInit() {
debugger;
this.curr = localStorage.getItem('currentUser').slice(1);
this.Tsk.getFTRs(this.curr).subscribe(
res => {
this.tasks = res;
for (let i = 0; i < this.tasks.length; i++){
if (this.tasks[i].Status) {
this.msgs.push({ severity: 'error', summary: 'Task Assigned', detail: 'A new task has been assigned to you' })
}
}
},
error => console.log(error)
)}

Angular2 Data binding with data from service

I have this component
#Component({
templateUrl: './app/component/template/actualstate.template.html',
styleUrls: ['./app/component/style/actualstate.style.css'],
pipes: [MomentPipe, CapitalizePipe]
})
export class ActualStateComponent implements OnInit {
public room: Room;
constructor(private roomService: RoomService) {
roomService.roomSelected$.subscribe(room => this.onRoomSelected(room));
}
onRoomSelected(room: Room) {
this.room = room;
console.log("room", room);
}
}
and this other component
#Component({
templateUrl: './src/admin/template/admin.template.html',
styleUrls: ['./src/admin/style/admin.style.css'],
providers: [UserService]
})
export class AdminComponent{
constructor ( private roomService: RoomService) {
}
onClick () {
this.roomService.selectRoom("","");
this.router.navigate(['ActualState']);
}
}
}
, this service :
#Injectable() 
export class RoomService {
private route_room = "public/mock/room.json";
public roomSelected$: EventEmitter<Room>;
constructor (private http: Http) {
this.roomSelected$ = new EventEmitter();
}
public selectRoom (subdomain: string, id: string) {
// pick the right room
let room = ...
this.roomSelected$.emit(room);
}
private handleError (error: Response) {
return Observable.throw(error.json().error || 'Server error');
}
}
And this template :
<div class="actual-state" *ngIf="room">
<h3>Salle {{ room.name }}
</h3>
</div>
The purpose is :
Admin component (user click on some button)
-> Listener OnClick calls a method on service roomService
-> roomService emit an event (that is public)
-> appComponent listen to this event (.subscribe)
I have no clue why this is not working. The <h3> is never showing .. even though the console.log(room) display something in the console...
How does this data binding working ? Because it just looks like data are not two-way bound
...
EDIT : i understood the problem, it was related to the routing i made. in fact i did'nt understand the fact that component of a route is destroyed when you change the route
I guess you need to subscribe
return this.http.get(this.route_room)
.map(res => res.json())
.do(data => {
this.roomSelected$.emit(data);
})
.subscribe(value => {})
.catch(this.handleError);

How can I get templateUrl in Component programmatically?

If I have a AngularDart Component:
#Component(selector: "my-selector",useShadowDom: false,
templateUrl: "packages/test/test.html")
class MyComponent {
MyComponent() {
...
}
...
}
How can I get the templateUrl programmatically?
I want to avoid a constructor with an Element injected. An injected Injector would be OK.
Found the answer:
#Component(selector: "my-selector", useShadowDom: false,
templateUrl: "packages/test/test.html")
class MyComponent {
Injector _injector;
MyComponent(this._injector) {
}
String get url {
DirectiveMap _directiveMap = _injector.get(DirectiveMap);
var tuples = _directiveMap['my-selector'];
//Validate.isTrue(tuples[0].directive is Component);
Component annotation = tuples[0].directive;
//_logger.info("TemplateUrl: ${annotation.templateUrl}");
return annotation.templateUrl;
}
}

Resources