Angular 4 – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Mar 2019 08:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Angular 4 – AppDividend https://appdividend.com 32 32 Angular HTTP Request Tutorial Example https://appdividend.com/2017/10/06/angular-http-request-tutorial-example/ https://appdividend.com/2017/10/06/angular-http-request-tutorial-example/#comments Fri, 06 Oct 2017 15:40:50 +0000 http://localhost/appdividend/?p=1128 Angular HTTP Request Tutorial

Angular HTTP Request Tutorial Example is today’s topic. Most of the front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the XMLHttpRequest interface and the fetch() API.  With HttpClient, @angular/common/http provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest interface exposed by browsers. If you want […]

The post Angular HTTP Request Tutorial Example appeared first on AppDividend.

]]>
Angular HTTP Request Tutorial

Angular HTTP Request Tutorial Example is today’s topic. Most of the front-end applications communicate with the backend services over an HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the XMLHttpRequest interface and the fetch() API.  With HttpClient@angular/common/http provides a simplified API for HTTP functionality for use with Angular applications, building on top of the XMLHttpRequest interface exposed by browsers.

If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.

Angular HTTP Request Tutorial

Here, I have used Angular CLI for the demonstration purpose.

Step 1: Do one Angular Project.

First, you need to install Angular CLI globally in your PC.

Then, go to the terminal and hit the following command.

ng new ngHTTPClient

So, it will create some boilerplates and also install all the NPM modules dependencies.

Step 2: Create a backend data.

If you have followed my Laravel 5.5 Angular 4 Tutorial Example From Scratch article then, in that section, I have described how to post the request data to the Laravel API server.

Now, For this example, I am using online JSON service to fetch the data from the server.

You can request the data to this URL: https://jsonplaceholder.typicode.com

Step 3: Include the HttpClient Module.

We need to include the module into the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Making a request for JSON data.

// app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('https://jsonplaceholder.typicode.com').subscribe(data => {
      console.log(data);
    });
  }
}

The above code is perfect. And you will see the console output.

But in some cases, the output will not be there because of CORS problem.

You will find an error like this.

Failed to load https://jsonplaceholder.typicode.com/: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4200’ is therefore not allowed access

So, in the real-time application, if you are using Laravel or Node.js as a  backend, you can find the solution by just download and install the right package for it.

If you are a Laravel developer then, you can find the solution on the above-mentioned link.

This is how you can get and post the request to any API server and get the response.

You can find more on this URL: https://angular.io/api/common/http/HttpClient

Finally, Our Angular HTTP Request Tutorial is over.

 

The post Angular HTTP Request Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2017/10/06/angular-http-request-tutorial-example/feed/ 2
Angular Form Validation Example Tutorial https://appdividend.com/2017/09/25/angular-form-validation-example-tutorial/ https://appdividend.com/2017/09/25/angular-form-validation-example-tutorial/#comments Mon, 25 Sep 2017 13:42:58 +0000 http://localhost/appdividend/?p=1100 Angular Form Validation Example Tutorial

Angular Form Validation Example Tutorial is today’s topic. Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, an end to end tooling, and integrated best practices to solve development challenges. User actions such as clicking a link, pushing a button, and entering text raise DOM events. Forms are […]

The post Angular Form Validation Example Tutorial appeared first on AppDividend.

]]>
Angular Form Validation Example Tutorial

Angular Form Validation Example Tutorial is today’s topic. Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, an end to end tooling, and integrated best practices to solve development challenges. User actions such as clicking a link, pushing a button, and entering text raise DOM events. Forms are the mainstay of business applications. You use forms to log in, submit a help request, place an order, book a flight, schedule a meeting, and perform countless other data-entry tasks. Improve overall data quality by validating user input for accuracy and completeness.

Angular Form Validation Tutorial

You can find the full Angular Validation docs on this URL:

We are using Angular Reactive Validation Form.

Step 1: Make one Angular Project.

Install Angular globally by the following command.

npm install -g @angular/cli

After that, type the following command to make a project.

ng new ngValidation

Create some files and also install all the dependencies related project.

Next, go to the project root and type the following command to start the server and open the project.

cd my-app
ng serve --open

Step 2: Make one form inside app.component.html

We are going to create a form with one input for just basic understanding for Angular Forms.

First, we need to include Reactive Form in app.module.ts file.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule, ReactiveFormsModule
  ],

Now, we need to write the code to display the form.

<!--The whole content below can be removed with the new code.-->
<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <form [formGroup]="angForm" novalidate>
        <div class="form-group">
          <label class="center-block">Name:
            <input class="form-control" formControlName="name">
          </label>
        </div>
        <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
            <div *ngIf="angForm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
  </form>
<p>Form value: {{ angForm.value | json }}</p>
<p>Form status: {{ angForm.status | json }}</p>
</div>

Also, we need to update the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Form Validation Tutorial';
   angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
       name: ['', Validators.required ]
    });
  }
}

I am going to explain how it is working so bear with me.

Step 3: Explanation

There are two types of forms in Angular.

  1. Template Driven Forms
  2. Reactive Forms

Template Driven Forms

In this kind of form, we can write the forms in Angular template syntax with form syntax directives.

Following are the steps to build template driven forms.

  1. Create the component that controls the form.
  2. Create a template with the initial form layout.
  3. Bind data properties to each form control using the two-way data-binding syntax.
  4. Add an attribute to each form-input control.
  5. Add custom CSS to provide visual feedback.
  6. Show and hide validation-error messages.
  7. Handle form submission with ngSubmit.
  8. Disable the form’s Submit button until the form is valid.

Reactive Forms

We have used Reactive Forms in our example in this article. 

Reactive forms is an Angular technique for creating forms in a reactive style. Angular reactive forms facilitate a reactive style of programming that favors explicit management of the data flowing between a non-UI data model (typically retrieved from a server) and a UI-oriented form model that retains the states and values of the HTML controls on the screen. Reactive forms offer the ease of using reactive patterns, testing, and validation.

Example

// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Form Validation Tutorial';
   angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
       name: ['', Validators.required ]
    });
  }
}

First, we need to import some of the modules from the @angular/forms.

  1. FormGroup
  2. FormBuilder
  3. Validators

Also, we need have imported ReactiveFormsModule in app.module.ts file. 
Then, we have taken angForm of the type of FormGroup.

// app.component.ts

constructor(private fb: FormBuilder) {
    this.createForm();
}

We have used form builder to handle all the validation. So in that constructor, we are creating a form with the validation rules.

// app.component.ts

createForm() {
  this.angForm = this.fb.group({
       name: ['', Validators.required ]
  });
}

In this code, I have assigned the Validation rules to the Form Object.

<form [formGroup]="angForm" novalidate>
        <div class="form-group">
          <label class="center-block">Name:
            <input class="form-control" formControlName="name">
          </label>
        </div>
        <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
            <div *ngIf="angForm.controls['name'].errors.required">
            Name is required.
          </div>
        </div>
  </form>
<p>Form value: {{ angForm.value | json }}</p>
<p>Form status: {{ angForm.status | json }}</p>

In this HTML code, I have assigned the global form group object called angForm. This is the top-level object.

All the inner form controls are like the children to them. We can also access its values.

I have used the conditional statement, if a user has touched the input field but not enter the values then, it displays the message. If user blurs the input field without any values then also it gives an error message.

 

Angular Reactive Form Validation

Step 5: Complete Form And Its Code

I am writing important files.

<!-- app.component.html -->

<div class="container">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <form [formGroup]="angForm" novalidate>
        <div class="form-group">
            <label>Name:</label>
            <input class="form-control" formControlName="name" type="text">
        </div>
        <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
            <div *ngIf="angForm.controls['name'].errors.required">
              Name is required.
            </div>
        </div>
         <div class="form-group">
            <label>Address:</label>
            <input class="form-control" formControlName="address" type="text">
        </div>
        <div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
            <div *ngIf="angForm.controls['email'].errors.required">
              email is required.
            </div>
        </div>
        <button type="submit"
            [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success">
            Save
        </button>
  </form>
  <br />
  <p>Form value: {{ angForm.value | json }}</p>
  <p>Form status: {{ angForm.status | json }}</p>
</div>

app.component.ts file looks like this.

// app.component.ts

import { Component } from '@angular/core';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Form Validation Tutorial';
   angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
       name: ['', Validators.required ],
       address: ['', Validators.required ]
    });
  }
}

 

Angular 4 Form Validation Example From Scratch

Fork Me on Github

This is it for Angular Form Validation article.

Thanks for the reading.

The post Angular Form Validation Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2017/09/25/angular-form-validation-example-tutorial/feed/ 2
Angular Router Tutorial Example https://appdividend.com/2017/09/23/angular-router-tutorial-example/ https://appdividend.com/2017/09/23/angular-router-tutorial-example/#comments Sat, 23 Sep 2017 21:40:58 +0000 http://localhost/appdividend/?p=1091 Angular Router Tutorial

Angular Router Tutorial Example is today’s main topic. The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. For Single Page Application, Routing is the one and only tool or we can say module to navigate the pages to pages. So, let […]

The post Angular Router Tutorial Example appeared first on AppDividend.

]]>
Angular Router Tutorial

Angular Router Tutorial Example is today’s main topic. The Angular CLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. For Single Page Application, Routing is the one and only tool or we can say module to navigate the pages to pages. So, let us get started Angular 4 Router Tutorial or just Angular Router Tutorial.

Angular Router Tutorial

You can find its documentation on this website.

Step 1: Install The Angular Project.

Install Angular CLI globally on your system by typing the following command.

npm install -g @angular/cli

Now, create one project called ngRouter.

ng new ngRouter

Serve the application by the following command.

cd my-app
ng serve --open

Step 2: Make three components for the application.

Create one directory inside src  >>  app folder called components.

Next, make three components by typing the following command.

ng g c home
ng g c about
ng g c dashboard

It creates a separate folder inside src  >>  app directory, we need to move all these three folders inside components folder for better project structure.

Step 3: Routing and Navigation.

The Angular Router enables navigation from one view to the next as users perform application tasks.

First, we need to import the routing modules inside our app.module.ts file.

// app.module.ts

import { RouterModule } from '@angular/router';

imports: [
    BrowserModule, RouterModule
],

Configuration

When you have created the components, it’s by default path is different and now we have moved the components, so now its path is different. So, first, we need to change that path in app.module.ts file.

// app.module.ts

import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

Okay, now we need to configure the routes. So make one file inside app directory called routerConfig.ts file.

Write the following code in it.

// routerConfig.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { AboutComponent } from './components/about/about.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';

export const appRoutes: Routes = [
  { path: 'home', 
    component: HomeComponent 
  },
  {
    path: 'about',
    component: AboutComponent
  },
  { path: 'dashboard',
    component: DashboardComponent
  }
];

We have defined one array and inside that array, we have registered the different routes with their components. Finally, we have exported it.

Now, import this object inside app.module.ts and register the module.

// app.module.ts

import { appRoutes } from './routerConfig';

imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes)
],

Step 4: Define the Router outlet.

In the app.component.html file, write the following code.

<!-- app.component.html  -->

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <nav>
    <a routerLink="home" routerLinkActive="active">Home</a>
    <a routerLink="about">About</a>
    <a routerLink="dashboard">Dashboard</a>
  </nav>
  <router-outlet></router-outlet>
</div>

Now, we have already changed the title inside app.component.ts file.

// app.component.ts

title = 'Angular Router Tutorial';

Start the app by the following command.

ng serve --open

After webpack compiles successfully, we can see the following page at the http://localhost:4200/home

 

Angular 4 Router Tutorial With Example 2017

Our basic Angular Router Tutorial is over. Thanks for the reading.

The post Angular Router Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2017/09/23/angular-router-tutorial-example/feed/ 19
Laravel 5.5 Angular 4 Tutorial Example From Scratch https://appdividend.com/2017/09/22/laravel-5-5-angular-4-tutorial-example-scratch/ https://appdividend.com/2017/09/22/laravel-5-5-angular-4-tutorial-example-scratch/#comments Fri, 22 Sep 2017 13:54:13 +0000 http://localhost/appdividend/?p=1075 Laravel 5.5 Angular 4 Tutorial

Laravel 5.5 Angular 4 Tutorial Example From Scratch is today’s topic. Laravel is PHP Web Application Framework. Angular 4 or just Angular is Popular Front End Framework for creating a client-side application. Today we will see how we can use both and how we can interact with each other via an API. We simply build one interface […]

The post Laravel 5.5 Angular 4 Tutorial Example From Scratch appeared first on AppDividend.

]]>
Laravel 5.5 Angular 4 Tutorial

Laravel 5.5 Angular 4 Tutorial Example From Scratch is today’s topic. Laravel is PHP Web Application Framework. Angular 4 or just Angular is Popular Front End Framework for creating a client-side application. Today we will see how we can use both and how we can interact with each other via an API. We simply build one interface in Angular 4 Application and then call an API to store the data. This is just a basic Item Storage Application using Angular 4 and Laravel 5.5. This example is a showcase of how we can use both to create a full stack application and how we can connect with an API.

Laravel 5.5 Angular 4 Tutorial

First, we are going to set up an AngularJS project at the client side. For that, you can use angular-cli for boilerplate for our application. You can find this on Angular 4 website Link: Set up the Development Environment

Step 1: Setup an Angular 4 Environment.

First, we need to install Angular CLI globally. So type the following command.

npm install -g @angular/cli

Okay, now we need to create one project, let us call it ng4tutorial.

Type the following command in your terminal.

ng new ng4tutorial

It will create some files and folders and also install all the front end dependencies.

After install, type the following command.

cd ng4tutorial
ng serve --open

Step 2: Create one form to enter the data.

Angular 4 is totally modular. All the component files reside in the src  >>  app folder.

We are using Bootstrap CSS Framework to design our form. So I have downloaded bootstrap CSS file in src  >>  assets directory called app.css file.

Our index.html file looks like this.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ng4app</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/assets/app.css" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
</body>
</html>

All the public static files are served from the assets folder.

For creating the form, we need to modify the app.component.html file. This file resides in src  >>  app directory.

<!--The whole content below can be removed with the new code.-->
<div class="container">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <hr />
    <form>
      <div class="form-group">
        <label for="name">Item Name:</label>
        <input type="text" class="form-control">
      </div>
      <div class="form-group">
        <label for="price">Item Price:</label>
        <input type="text" class="form-control">
      </div>
      <button type="submit" class="btn btn-primary">Add</button>
    </form>
</div>

Our app.component.ts file looks like this.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Laravel Angular 4 App';
}

Our Form looks like this.

Laravel AngularJS Tutorial

 

Step 3: Handle the input data.

First of all, we need to import two modules in the app.module.ts file.

  1. FormsModule
  2. HttpModule

And these modules are also included in the import array. So our src  >>  app  >>  app.module.ts file looks like this.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule, HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, we need to include Angular Form Object into our HTML. Our final code of app.component.ts looks like this.

// app.component.ts

<div class="container">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <hr />
    <form (ngSubmit)="onSubmit(fm)" #fm="ngForm">
      <div class="form-group">
        <label for="name">Item Name:</label>
        <input type="text" class="form-control" ngModel name="name">
      </div>
      <div class="form-group">
        <label for="price">Item Price:</label>
        <input type="text" class="form-control" ngModel name="price">
      </div>
      <button type="submit" class="btn btn-primary">Add</button>
    </form>
</div>

We have added one attribute to the input box called “ngModel“. This attribute tells angular that, how many values are there in the HTML Form. It creates an object and later after submits we can access that object and pull out the values from it.

<form (ngSubmit)="onSubmit(fm)" #fm="ngForm">

It is the way to tell AngularJS that it needs to create an object that describes the whole form element and its values.

After press the submit, onSubmit() function is called and in that we can get all the values of the form.

// app.component.ts

import { Component } from '@angular/core';
import { Item } from './Item';
import { NgForm }   from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Laravel Angular 4 App';
  onSubmit(form: NgForm){
  	console.log(form.value);
  }
}

Here onSubmit() function, we get all the form values. Now, we can send the POST request to the Laravel Server.

Step 4: Send the data to the Laravel server.

Next step would be to call HTTP Service to handle the POST request.

First, we need to import two modules in app.component.ts file.

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';

The further step would be to call that service. This is my full code of the app.component.ts file.

// app.component.ts

import { Component, Injectable } from '@angular/core';
import { Item } from './Item';
import { NgForm }   from '@angular/forms';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
	constructor(private _http: Http){}
        private headers = new Headers({'Content-Type': 'application/json'});
  	title = 'Laravel Angular 4 App';
  	onSubmit(form: NgForm): Promise <Item>{
        return this._http.post('http://127.0.0.1:8000/api/items', JSON.stringify(form.value), {headers: this.headers})
  		   .toPromise()
    	           .then(res => res.json().data)
    	            .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
  console.error('An error occurred', error); // for demo purposes only
  return Promise.reject(error.message || error);
  }
}

I have used Promise and Observables. Also imported it on the Top.

Step 5: Create A Laravel Backend For the Request.

Create one Laravel project by typing the following command.

composer create-project laravel/laravel --prefer-dist ng4Laravel55

Edit the .env file to set the MySQL database credentials.
Next, switch to your command line interface and type the following command.

php artisan make:model Item -m

Navigate to the migration file in the database  >>  migrations  >>  create_items_table and copy the following code into it.

<?php

// create_items_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}

Type the following command in your terminal.

php artisan migrate

Create one controller called ItemController.

php artisan make:controller ItemController

Register the routes in the routes  >>  api.php file.

Route::post('items', 'ItemController@store');

In the Item.php model, we need to include the $fillable property to prevent the mass assignment exceptions.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = ['name', 'price'];
}

Write the store function in the ItemController.php file to save the data into the database.

<?php

// ItemController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $item = new Item([
          'name' => $request->get('name'),
          'price' => $request->get('price')
        ]);
        $item->save();
        return response()->json('Successfully added');
    }
}

Start the Laravel Development server by the typing the following command.

php artisan serve

Step 6: Resolve CORS problem

Download the following Laravel Specific CORS package to avoid this issue and follow the steps.

composer require barryvdh/laravel-cors

Add the Cors\ServiceProvider to your config/app.php provider’s array.

Barryvdh\Cors\ServiceProvider::class,

To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.phpclass:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

You can publish the config using this command:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Now, try again, it will save the data into the database. I have not set the redirect after saving the data but will set in short, while you can check the values in the database.

For now, this is enough, we can build CRUD functionality in the next article. So stay tuned.

This is the basic example of Laravel 5.5 Angular 4 Tutorial.

 

The post Laravel 5.5 Angular 4 Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/09/22/laravel-5-5-angular-4-tutorial-example-scratch/feed/ 39