Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Henrique Buzin

Angular 2 e PHP

Recommended Posts

Olá, Sou iniciante em angular 2, estou desenvolvendo uma aplicação utilizando Angular 2 e PHP, mas quando tendo pegar os valores do json dá erro: ERROR Error: Error trying to diff 'Grand Turismo'. Only arrays and iterables are allowed e ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 23, nodeDef: Object, elDef: Object, elView: Object}.

Este é o back-end, está bem simples:

<?php

    use \Psr\Http\Message\ServerRequestInterface as Request;

    use \Psr\Http\Message\ResponseInterface as Response;

    header("Access-Control-Allow-Origin: *");

    require 'vendor/autoload.php';

    $app = new \Slim\App;

    $app->get('/games', function (Request $request, Response $response){

        $games = array();

        $games = array(

            "name" => "Grand Turismo",

            "category" => "PS4",

            "price" => "199.99",

            "quantity" => "8",

            "production" => "true",

            "description" => "Eleito o melhor jogo de corrida."

        );

        return json_encode($games);

    });

    $app->run();
?>

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 { PopupModule } from 'ng2-opd-popup';

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

import { FooterComponent } from './footer/footer.component';
import { HeaderComponent } from './header/header.component';
import { GamesListingComponent } from './listing/games/games-listing.component';
import { PlatformsListingComponent } from './listing/platforms/platforms-listing.component';
import { routing } from './app.routes';

import 'rxjs/add/operator/map';

@NgModule({
  declarations: [
    AppComponent, 
    PlatformsListingComponent, 
    FooterComponent,
    HeaderComponent,
    GamesListingComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    HttpModule,
    PopupModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

games-listing.component.ts

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

import {Popup} from 'ng2-opd-popup';

@Component({
    moduleId: module.id,
    selector: 'app-games-listing',
    templateUrl: './games-listing.component.html',
    styleUrls: ['./games-listing.component.css']
})
export class GamesListingComponent{ 

    games: Object[] = [];

    constructor(http: Http, private popup:Popup){

        http.get('http://localhost:80/lightning/server/index.php/games')
        .map(res => res.json()).subscribe(games => {

            this.games = games;

            console.log(this.games);

        }), erro => console.log(erro);

    }

    ClickButton(){

        this.popup.options = {

            header: "Your custom header",

            color: "#5cb85c", // red, blue....

            widthProsentage: 40, // The with of the popou measured by browser width

            animationDuration: 1, // in seconds, 0 = no animation

            showButtons: true, // You can hide this in case you want to use custom buttons

            confirmBtnContent: "OK", // The text on your confirm button

            cancleBtnContent: "Cancel", // the text on your cancel button

            confirmBtnClass: "btn btn-default", // your class for styling the confirm button

            cancleBtnClass: "btn btn-default", // you class for styling the cancel button

            animation: "fadeInDown" // 'fadeInLeft', 'fadeInRight', 'fadeInUp', 'bounceIn','bounceInDown'

        };

        this.popup.show(this.popup.options);

    }

    YourConfirmEvent(){

        alert('You cliked confirm');

    }

    YourCancelEvent(){

        alert('You cliked cancel');

    }

}

games-listing.component.html

<table class="table table-striped">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Categoria</th>
      <th>Fabricante</th>
      <th>Ver mais...</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let game of games">
      <td>{{game.name}}</td>
      <td></td>
    </tr>
  </tbody>
</table>

Se precisar de algum outro código, só avisar que passo.

Agradeço desde já.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
    • Por violin101
      Caros amigos, saudações.
       
      Gostaria de tirar uma dúvida com os amigos, referente a PDV.
       
      Estou escrevendo um Sistema com Ponto de Vendas, a minha dúvida é o seguinte, referente ao procedimento mais correto.

      Conforme o caixa vai efetuando a venda, o Sistema de PDV já realiza:
      a baixa direto dos produtos no estoque
      ou
      somente após concretizar a venda o sistema baixa os produtos do estoque ?
       
      Grato,
       
      Cesar
       
    • Por violin101
      Caros amigos do grupo, saudações e um feliz 2025.
       
      Estou com uma pequena dúvida referente a Teclas de Atalho.

      Quando o Caps Lock está ativado o Comando da Tecla de Atalho não funciona.
      ou seja:
      se estiver para letra minúscula ====> funciona
      se estiver para letra maiúscula ====> não funciona
       
      Como consigo evitar essa falha, tanto para Letra Maiúscula quanto Minúscula ?

      o Código está assim:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'r' ) return;// Não é Ctrl+r, portanto interrompemos o script evt.preventDefault(); });  
      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, poderiam me ajudar.

      Estou com a seguinte dúvida:
      --> como faço para para implementar o input código do produto, para quando o usuário digitar o ID o sistema espera de 1s a 2s, sem ter que pressionar a tecla ENTER.

      exemplo:
      código   ----   descrição
           1       -----   produto_A
       
      Grato,
       
      Cesar
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.