Category Archives: angular

Trouble with Angular 2 http.get method

Salutations. I'm trying to learn Angular 2 by rebuilding the front end of a project I did previously while using the same back end code. The original project used jQuery on the front end and PHP in the back. I'm at the point where I want to start hooking my the front end to the back but I can't seem to get it to work.

Currently I have my original back end code running on apache2 on localhost and test Angular app is running on localhost:4200. The back end file I'm trying to access is at ajax.php (path is 'localhost/pokemon/ajax.php') and I have a line in that file to log an error whenever that file is referenced.

When I do http.get from my Angular 2 service and log the result on my component, I get [object Object] And the ajax.php doesn't log the message so it seemingly hasn't been called.

Here's my code. I The functions in question are near the bottom of each file.

hero.service.ts

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';

  constructor(
    private messageService: MessageService,
    private http: HttpClient
  ) { }


  getHeroes (): Observable<Hero[]> {
    //return this.http.get<Hero[]>(this.heroesUrl)
    return null;
  }

  getHero(id: number): Observable<Hero> {
    // TODO: send the message _after_ fetching the hero
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    return of(HEROES.find(hero => hero.id === id));
  }

  //calls http.get
  testFunc() {
    console.log("Test func is being called in the service");
    return of(this.http.get('localhost/pokemon/ajax.php?method=getTypes'));
  }
}

And the component I'm trying to test with

heroes.component.ts

import { Component, OnInit } from '@angular/core';

import { Hero } from '../hero';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    console.log("Init is being called");
    //this.getHeroes();
    this.testFunc();
  }

  //calls the test function
  testFunc(): void {
    console.log("Test function is being called");
    this.heroService.testFunc()
      .subscribe(
        data => console.log("Got this: " + data),
        err => console.log("Error " + err),
        () => console.log("Done!")
      );
  }
}

I also tried to get the data from a live server with the same app but the result was the same.

Thanks!

apache, htacces multiple document roots?

I have a direcory structure that looks like this for my application:

->app/
->app/index.php
->client/
->client/dist/index.html

the vhost for the domain is which sets the document root to projects root directory:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.

        ServerName lfc-v2.ten

        ServerAdmin [email protected]
        DocumentRoot /mnt/c/Development/tendesign/lfc-v2/

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

        <Directory /mnt/c/Development/tendesign/lfc-v2>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

I am not really that good at vhosts and htaccess, so here is what I need to do in my htaccess

  1. All requests to the domain.tld should go to <docroot>/client/dist
  2. All requests to the domain.tld/app should go to <docroot>/app

This is what I have so far, but I seem to be getting 404 errors in the client

RewriteEngine on

RewriteCond "/%{REQUEST_URI}" -f [OR]
RewriteCond "/%{REQUEST_URI}" -d
RewriteRule ^/?(.*)$ /client/dist/$1 [L]

RewriteCond "/app%{REQUEST_URI}" -f [OR]
RewriteCond "/app%{REQUEST_URI}" -d
RewriteRule ^/?(.*)$ /app/$1 [L]

Angular redirect with .htaccess

 RewriteEngine On
 # If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested pattern is file and file doesn't exist, send 404
RewriteCond %{REQUEST_URI} ^(\/[a-z_\-\s0-9\.]+)+\.[a-zA-Z]{2,4}$
 RewriteRule ^ - [L,R=404]

 # otherwise use history router
 RewriteRule ^ /webapp/index.html

If a person navigates to example.com, I want it to redirect to example.com/webapp/index.html

But only if they are on the root of the domain.

Not able to deploy Angular 4 in production

I have tried this answer and can confirm that mod_rewrite is enabled on my hosting

And I have tried the following .htaccess configurations from various answers and sites but none helped.I'm not able to debug where the problem is.

From the official site:

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

From some gist

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

And many others but all are giving 404 errors. Any way to debug it. I'm using ng build --prod to make a dist then hosting on dev.example.com and trying to access dev.example.com/home which is available when accessed from dev.example.com Could it be due to sub domain?

Noticed one more thing:

If I add gibberish to my htaccess file then I only get a 500 error when I try to access some files like dev.example.com/hello otherwise when I access dev.example.com it's working fine without error.

How to make mod_rewrite for multiple web app in one sub domain

I have a problem on rewrite rule in .htaccess, mainly because I never personally use Apache. Here is my folder

--root-folder -------------index.html -------------another_app0_folder -------------------------------index.html -------------another_app1_folder -------------------------------index.html -------------another_app2_folder --------------------------------public --------------------------------------index.php

Basically I want to access those apps on one domain. Let's say if I want to access mydomain.com that will be my root folder, then if I want to access app 1 that will be mydomain.com/app1. I found the trickiest part is the last app, because I want to access it one 1 /, also I want to rewrite the URL, I understand if I can rename the folder with whatever but I want to make the URL after / is not the name of the folder. Can anyone help me on that?

Additional info: the root folder, app 0, and app 1 are Angular 4 projects and app 2 is a Lumen project

PS: Found out recently, renaming folder made the browser redirects me to the root folder every time I hit refresh

Angular 5 lazy loaded module doesn’t work on refresh

Note about this issue: I noticed it only happens using certain types of build process. Since I'm using angular-cli this error will appear everytime I compile the application using ng build. The only exception is when I use ng build --prod. I use any other flag I used to use, such as --dev --aot then I'll get the error where I can't refresh the page.

When using ng build --prod the refresh on the page will keep the application running as expected. But during development it means I need to run the command everytime a change is made on the code, otherwise I'll get errors like:

(void 0) is not a function

I'm trying to use Angular 5 lazy loaded modules using wamp server but I'm having problems when I refresh the page using lazy loaded modules. This is my routing configuration:

// Root routing config
export const mainRouting: Routes = [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    {
        path: '',
        component: PortalComponent,
        canLoad: [ResolveGuard],
        children: [
            { path: 'home', component: HomeComponent },
            {
                path: 'page',
                loadChildren: './modules/page/page.module#PageModule'
            },
            {
                path: 'user',
                component: UserComponent,
                children: [
                    { path: 'profile', component: ProfileComponent },
                    { path: 'config', component: ConfigComponent },
                ]
            }
        ]
    },
];

// LazyLoaded routing config
export const pageRouting: Routes = [
    {
        path: '',
        children: [
            { path: 'about', component: PageAboutComponent },
            { path: 'condition', component: PageConditionComponent }
        ]
    }
];

Everything is working as expected. I can navigate to the home page of the application, I can access the lazy loaded routes (page/about and page/condition), the PageModule is loading only on demand, etc..

The problem is when I'm on the url /page/about (for example) and I refresh the page, then I get a 404 error.

If I'm on the url /user/profile and refresh the page, the application load as expected, because the user is not lazyloaded, it's within the main module.

I'm already using this .htaccess configuration

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

But only in this specific case it's not working. Is there a way to solve this issue?

Unable to deploy Angular 5 using dist folder in WAMP server

I am unable to make my angular 5 app work in WAMP server. I have read many other stack overflow posts and tried a few options.

Steps to produce dist folder :

step 1 - ng build --prod --base-href "/dist/".

step 2 : Copy the dist/* files to DOCUMENT_ROOT.

dist in root folder

enter image description here

step 3 - restarted WAMP server

Step 4 - localhost . dist folder shows in WAMP

enter image description here

step 5 :localhost/dist and localhost/dist/index.html - nothing works

step 6: I changed base href to "/dist/" and restarted WAMP - This opened index file Dint work

step 7 - based on deployment method given in angular site -https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml

i created .htaccess file and copied the following code and have put the file in the dist folder enter image description here

enter image description here

Still routing not working . Please please help. struggling with this for last 3 days !

Angular 2: hide route component

I have a website built around angular 2 running on Apache. The same website (and same API) is used by different "groups". Let's say there are two groups: bees and wasps. My angular routing file looks like this:

{
        path: '',
        redirectTo: 'groupe/1',
        pathMatch: 'full'
    },
    {
        path: 'groupe',
        children: [
            {
                path: ':groupe',
                children: [
                    {
                        path: '',
                        component: HomePage,
                    },
...

To access a group, I can then simply go to http://myws.com/group/1 (for bees) and http://myws.com/group/2 (for wasps). Pages are then basically the same for each group (with different content, loaded from an API), like: http://myws.com/group/1/page/21.

Now the tricky part. First I want to access each "group" from a simplified, explicit URL: like http://myws.com/bees. I can do this by adding the following code to the router :

{
    path: 'bees',
    redirectTo: 'groupe/1',
    pathMatch: 'prefix'
},

Problem is, the route changes in the URL back to /group/1. Is there a way to make the /bees permanent, hiding /group/1 ?

Now, I also want to access my bees group from a specific domain, like http://www.bees.com. Pages should render like http://www.bees.com/page/21 Is there a way with angular or Apache to do this?

Response for preflight has invalid HTTP status code 403 in Angular 2

I am working with an Angular 2 & Ionic 2 app. I had to change to another server for testing and the API has stopped working with the below error message:

Response for preflight has invalid HTTP status code 403

I added this to .htaccess

<IfModule mod_headers.c>
    Header append Vary User-Agent env=!dont-vary
    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</IfModule>

This on my angular provider:

  loginUser(data): Observable<any> {
    let username: string = data.username;
    let password: string = data.password;
    let headers: Headers = new Headers();
    let url = this.domain + "/wp-json/wp/v2/users/me?context=edit";
    let bt = btoa(username + ":" + password);

    this.storage.save('bt', {'bt':bt});
    headers.append("Authorization", "Basic " + bt);
    headers.append('Access-Control-Allow-Headers', 'Content-Type');
    headers.append("Content-type", "application/x-www-form-urlencoded");
    headers.append('Access-Control-Allow-Origin', '*');

    return this.http.get(url, {headers: headers}).map(res => res.json())
  }

Also, enabled a chrome plugin I have for CORS issues which is enabled and works on other cases when I am on localhost projects.

I tried everything I found and I am not sure what else I could do.

Checking the network tab on Chrome Dev Console, the response is this one:

<HTML>
<HEAD>
<TITLE>403 Forbidden</TITLE>
</HEAD>
<BODY>
<H1>Forbidden</H1>
You do not have permission to access this document.
<P>
<HR>
<ADDRESS>
Web Server at my domain here
</ADDRESS>
</BODY>
</HTML>

Based on the answers, this is my rewrite rules aswell:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>