Angular4で外部モジュール内のcomponentのセレクターを使えるようにする

ログイン関係の外部モジュールのセレクターを使いたかったので、一部切り分けてモジュール化してみました〜

ちなみに、exportしたモジュールは使いたいモジュールのところでインポートすれば問題なく使用できます

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  exports: [TaskCardComponent] <==  component をexport することで外部モジュール内でもselectorを使用することができる!
})
export class TaskModule{}

参考にした記事
Angular 2 Use component from another module

Active adminで comment モデルを生成できない

active adminでモデルを操作できるようにファイルを生成しようとしたら以下のエラーが出てきました〜

/Users/hiyashikyuri/.bundle/ruby/2.3.0/activeadmin-adcc7e379d1a/lib/active_admin/resource_collection.rb:53:in `raise_if_mismatched!': You're trying to register ActiveAdmin::Comment as Comment, but the existing ActiveAdmin::Resource config was built for Comment! (ActiveAdmin::ResourceCollection::ConfigMismatch)

どうやらバグらしいので、Commentとは異なる名前をつけることで解決します!

# 名前は自由なので任意でつけてください
ActiveAdmin.register Comment, :as => "TestComment" do

end

参考にした記事
ActiveAdmin Comment model not working properly

Nativescirpt cameraモジュールの使い方

インターネットで見つけたチュートリアルには以下のようにインポートすることでカメラにアクセスできると書いてありましたが、
バージョンによっては?できないみたいで

// これはできない例
import {Component} from "@angular/core";
import *as Camera from "camera";

nativescript-cameraというカメラモジュールをインポートしてから起動すると無事に動きます!

$ npm install nativescript-camera --save
$ tns livesync android

ちなみにこんな感じで簡単に関数作れます

// component 側
import {Component} from "@angular/core";
// このようにインポートすることで使用可能になる
import Camera = require("nativescript-camera");

@Component({
    moduleId: module.id,
    selector: "test",
    templateUrl: "./test.component.html",
})

export class TestComponent {

    public capture() {
        Camera.takePicture().then((picture) => {
            //何かしらの処理を加える
        })
    }
}

// html側
// angularでは(click)を頻繁に使っていましたけど、nativescriptでは(tap) を使用するみたいです
// tapするとカメラが起動します
<ActionBar title="Testのバー">
    <NavigationButton text="戻る"></NavigationButton>
    <ActionItem text="カメラを起動する"  (tap)="capture()"></ActionItem>
</ActionBar>
<StackLayout>
    <Label text="Hello world"></Label>
</StackLayout>

参考にした記事
Camera

Nativescript ルーティングでエラーが発生する

最近始めたNativescriptで絶対できているはずなのに、なぜかルーティンが動かずに以下のエラーが出てきました

W/System.err(17364): 	at com.tns.Runtime.callJSMethodNative(Native Method)
W/System.err(17364): 	at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1021)
W/System.err(17364): 	at com.tns.Runtime.callJSMethodImpl(Runtime.java:903)
W/System.err(17364): 	at com.tns.Runtime.callJSMethod(Runtime.java:890)
W/System.err(17364): 	at com.tns.Runtime.callJSMethod(Runtime.java:874)
W/System.err(17364): 	at com.tns.Runtime.callJSMethod(Runtime.java:866)

問題だったのはcomponentに module.idを入れ忘れていたからでした

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

@Component({
    moduleId: module.id, // ここが抜けてた!!
    selector: "page1",
    templateUrl: "./page1.component.html",
})
export class Page1Component { }

devise token auth api をAngular4 でUIを実装する2

※angularの完成物のBitbucketのリンクです
Angular4-devise-token-auth

関連記事
全て連続しているので上から順に進めていっていただけるとわかりやすいと思います
devise token auth を使って簡単に早くAPIを作る1( api作成 )
devise token auth を使って簡単に早くAPIを作る2 ( jsonの出力 )
devise token auth api をAngular4 でUIを実装する1 ( angularのセットアップ )
devise token auth api をAngular4 でUIを実装する2 今回はここ
devise token auth api をAngular4 でUIを実装する3 ( 新規登録 )
devise token auth api をAngular4 でUIを実装する4 ( ログインしやすくする)
今回はログイン機能を構築することを目標に進めていきます

Angularの簡単な説明

Angularとはgoogleが主導で開発を進めているjavascriptのフレームワークです
最近ではvue.jsやreactと同じくらい流行っていると思いますが、これらとは異なり完全なフルスタックフレームワークです

個人的にはvueやreactの手軽さも好きなんですけど、ある程度の規模だったりtypescriptがデフォルトなので
コンパイルする際にエラーが出て来ることで早期にバグを防げる点ですごく利点があるなーと思ってます
ただ、小規模で利用する場合はオーバースペックになる可能性が高いので規模に合わせて使うのがいいかと

そんなAngularですが全体像はこちらです

引用

ARCHITECTURE OVERVIEW

Angularには大きく分けて

  • Component
  • service

があります

Componentはrailsで例えるとcontrollerで、Serviceはmodelです

基本的に使い方は同じでServiceに共通で使うロジックをまとめてComponentでそれらを呼び出し
エラーハンドリング等もここで行う感じです
ちなみにviewレンダリングもComponentでセットになっています

Serviceを作る

まずはserviceを作っていきます
ターミナルで

# appディレクトリに移動して
$ cd src/app/

# その後serviceを生成
$ ng g service auth
installing service
  create src/app/auth.service.spec.ts
  create src/app/auth.service.ts
  WARNING Service is generated but not provided, it must be provided to be used

ターミナルでng コマンドで生成すると以下のコードのように最低限必要な機能が備わっています
以下を編集してログインできるようしていきます

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

@Injectable()
export class AuthService {

  constructor() { }

}

編集後⬇︎

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

// 必要なモジュールをインポート
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class AuthService {

  // apiのurl
  private url = 'http://localhost:3000';

  constructor(private http: Http) {
  }


  // 引数にはログイン時に必要となる、emailとpasswordを入れる予定
  // headerはjsonだと明記する
  logIn(body: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.url + '/auth/sign_in', body, options).toPromise();
  }
}


// ログイン時のオブジェクトを定義
export class Login {
  constructor(public email?: string,
              public password?: string) {
  }
}

app.module.tsの編集

componentをターミナルで生成すると、自動的にapp.module.tsに追加されますが、
serviceは追加されません

なので、追加します

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';
// 追加
import {AuthService} from "./auth.service";

import {LoginComponent} from './login/login.component';
import {SignUpComponent} from './sign-up/sign-up.component';

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    SignUpComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [AuthService], //追加!
  bootstrap: [AppComponent]
})
export class AppModule {
}

Componentを作る

componentを生成する

$ ng g component login
installing component
  create src/app/login/login.component.css
  create src/app/login/login.component.html
  create src/app/login/login.component.spec.ts
  create src/app/login/login.component.ts
  update src/app/app.module.ts

こちらがデフォルトのコンポーネントです

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

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

  constructor() { }

  ngOnInit() {
  }

}

それでは先程と同様に修正を加えていきます

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

//AuthServiceとLoginクラスをインポート
import {AuthService, Login} from '../auth.service';

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

  // オブジェクトの初期化
  sign_in = new Login();

  constructor(private authService: AuthService) {
  }

  ngOnInit() {
  }

  data(): any {
    // ログイン時に必要なデータを作成
    let body = JSON.stringify({
      'email': this.sign_in.email,
      'password': this.sign_in.password
    });
    // auth serviceのloginメソッドを body を引数として呼び出す
    // その後responseをconsoleで表示
    this.authService.logIn(body).then((response: any) => {
      console.log(response);
    });
  }

}

componentの修正が終わったら次はviewサイドでbootstrapを使用することができるように
src/index.htmlにSDNを追加します

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular4DeviseTokenAuth</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- bootstrap を使用できるようにsdnを追加 -->
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>

Componentのviewを作成する

viewでは最低限のbootstrapを使うのでindex.htmlを編集

Componentを生成した際にhtmlを作られているので、フォームを修正します

<form>

  <div class="row">
    <h2>ログイン</h2>

    <div class="col-md-3 input-lg">
      <label>メールアドレス</label>
    </div>
    <div class="col-md-9">
      <input type="text" class="form-control input-lg" name="email" [(ngModel)]="sign_in.email">
    </div>
  </div>


  <div class="row">
    <div class="col-md-3 input-lg">
      <label>パスワード</label>
    </div>
    <div class="col-md-9">
      <input type="password" class="form-control input-lg" name="password" [(ngModel)]="sign_in.password">
    </div>
  </div>


  <div class="row">
    <div class="col-md-offset-3 col-md-9">
      <button type="submit" class="btn btn-danger btn-lg" (click)="data()">
        ログインする
      </button>
    </div>
  </div>
</form>

フォームを修正し終えたら、app.component.tsにlogin componentのセレクタを入れます

<div class="container-fluid">
  <div class="container">
    <app-login></app-login>
  </div>
</div>

これでログインは終わったので、実際にログインできるか試してみます

開発者環境を開いて、consoleもしくはnetoworkで確認してみましょう
データベースに登録されている情報が返却されていたら完璧です!

devise token auth api をAngular4 でUIを実装する1

※angularの完成物のBitbucketのリンクです
Angular4-devise-token-auth

関連記事
全て連続しているので上から順に進めていっていただけるとわかりやすいと思います
devise token auth を使って簡単に早くAPIを作る1( api作成 )
devise token auth を使って簡単に早くAPIを作る2 ( jsonの出力 )
devise token auth api をAngular4 でUIを実装する1 ( angularのセットアップ ) 今回はここ
devise token auth api をAngular4 でUIを実装する2
devise token auth api をAngular4 でUIを実装する3 ( 新規登録 )
devise token auth api をAngular4 でUIを実装する4 ( ログインしやすくする)

今回からは実際にAngular4を利用してapiとつなげていきます

※Angularとdevise token authを繋ぐライブラリneroniaky/angular2-tokenが存在しますが、4系に対応していない + 難しいコードや、ややこしいコードは書かないので、ライブラリを使わずにそのまま書いていきます。あと、今回はtypescriptやangularの最低限のベースを知っている方対象という前提なので、全く使ったことがない方は少し難しいかもしれませんので、docsなどを読んでからまた戻ってきていただけると嬉しいです!

node.jsのインストール

node.jsの最新バージョンを以下のリンクからインストールをおこなってください
node.js インストールページ

Angular CLIのインストール

angularにはangular cliという便利なライブラリがあります
このライブラリはターミナル上でコマンドを叩くだけでプロジェクトを作ったり
コンポーネントやサービスをジェネレートできるのでとても便利です

angular-cli詳細ページ

nodeを入れた後はこのコマンド一発で導入できます

$ npm install -g @angular/cli

プロジェクトを作る

無事にインストールが完了したら以下のコマンドでプロジェクトを生成します

$ ng new Angular4-devise-token-auth
installing ng
  create .editorconfig
  create README.md
  create src/app/app.component.css
  create src/app/app.component.html
  create src/app/app.component.spec.ts
  create src/app/app.component.ts
  create src/app/app.module.ts
  create src/assets/.gitkeep
  create src/environments/environment.prod.ts
  create src/environments/environment.ts
  create src/favicon.ico
  create src/index.html
  create src/main.ts
  create src/polyfills.ts
  create src/styles.css
  create src/test.ts
  create src/tsconfig.app.json
  create src/tsconfig.spec.json
  create src/typings.d.ts
  create .angular-cli.json
  create e2e/app.e2e-spec.ts
  create e2e/app.po.ts
  create e2e/tsconfig.e2e.json
  create .gitignore
  create karma.conf.js
  create package.json
  create protractor.conf.js
  create tsconfig.json
  create tslint.json
Successfully initialized git.
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Project 'Angular4-devise-token-auth' successfully created.

生成が終わったら、ディレクトリに移動し起動します
その後localhost:4200にアクセスすると

$ cd Angular4-devise-token-auth/
$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
Hash: 540eb6dc093fe60e4243                                                       d Time: 11622ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 158 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 3.63 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 10.5 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.4 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

app worksが表示されれば、これで準備は終了です

次の記事
devise token auth api をAngular4 でUIを実装する2

Nativescript cannot run your app in native emulator

nativescriptをandroidで走らせるとタイムアウトになって途中で止まってしまい、動作確認ができません

$ tns run android

Cannot run your app in the native emulator. Increase the timeout of the operation with the --timeout option or try to restart your adb server with 'adb kill-server' command. Alternatively, run the Android Virtual Device manager and increase the allocated RAM for the virtual device.

こちらのコードをで実行すると動きます!
ちなみに今回はエミュレーターで起動しましたが、個人的にはAndroid端末を持っている方は端末で動かした方が楽です

$ tns run android --emulator --timeout 0 

参考にした記事

Cannot run your app in the native emulator. #1609

Nativescriptプロジェクト開始後エラー

最近ネイティブスクリプトの勉強をしているのですが、プロジェクトを始めるたびになんかしらのエラーが発生します
ちょっと長いですが、こちらがエラー内容です

@angular/compiler/src/directive_normalizer.d.ts(39,72): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/directive_normalizer.d.ts(41,74): error TS2304: Cannot find name 'Promise'.
@angular/compiler/src/i18n/extractor.d.ts(14,33): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/i18n/extractor.d.ts(22,35): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/jit/compiler.d.ts(41,49): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/jit/compiler.d.ts(43,65): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/metadata_resolver.d.ts(67,104): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/resource_loader.d.ts(13,23): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/util.d.ts(32,18): error TS2304: Cannot find name 'Promise'.

@angular/compiler/src/util.d.ts(33,46): error TS2304: Cannot find name 'Promise'.
@angular/core/src/application_init.d.ts(17,27): error TS2304: Cannot find name 'Promise'.

@angular/core/src/application_ref.d.ts(116,76): error TS2304: Cannot find name 'Promise'.

@angular/core/src/application_ref.d.ts(132,110): error TS2304: Cannot find name 'Promise'.

@angular/core/src/application_ref.d.ts(162,67): error TS2304: Cannot find name 'Promise'.

@angular/core/src/application_ref.d.ts(164,101): error TS2304: Cannot find name 'Promise'.

@angular/core/src/linker/compiler.d.ts(43,49): error TS2304: Cannot find name 'Promise'.

@angular/core/src/linker/compiler.d.ts(51,65): error TS2304: Cannot find name 'Promise'.

@angular/core/src/linker/ng_module_factory_loader.d.ts(14,34): error TS2304: Cannot find name 'Promise'.

@angular/core/src/linker/system_js_ng_module_factory_loader.d.ts(28,25): error TS2304: Cannot find name 'Promise'.

@angular/core/src/util/lang.d.ts(12,53): error TS2304: Cannot find name 'Promise'.

@angular/router/src/config.d.ts(310,85): error TS2304: Cannot find name 'Promise'.

@angular/router/src/interfaces.d.ts(78,99): error TS2304: Cannot find name 'Promise'.

@angular/router/src/interfaces.d.ts(157,109): error TS2304: Cannot find name 'Promise'.
@angular/router/src/interfaces.d.ts(229,162): error TS2304: Cannot find name 'Promise'.
@angular/router/src/interfaces.d.ts(299,89): error TS2304: Cannot find name 'Promise'.
@angular/router/src/interfaces.d.ts(367,50): error TS2304: Cannot find name 'Promise'.
@angular/router/src/router.d.ts(285,70): error TS2304: Cannot find name 'Promise'.
@angular/router/src/router.d.ts(307,59): error TS2304: Cannot find name 'Promise'.
@angular/router/src/router_module.d.ts(186,23): error TS2304: Cannot find name 'Promise'.

@angular/router/src/utils/collection.d.ts(28,79): error TS2304: Cannot find name 'Promise'.

@types/core-js/index.d.ts(39,27): error TS2304: Cannot find name 'IterableIterator'.

@types/core-js/index.d.ts(226,38): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(231,35): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(236,37): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(327,13): error TS2300: Duplicate identifier 'log'.
@types/core-js/index.d.ts(349,33): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(350,31): error TS2304: Cannot find name 'IterableIterator'.

@types/core-js/index.d.ts(351,34): error TS2304: Cannot find name 'IterableIterator'.

@types/core-js/index.d.ts(352,34): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(353,34): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(354,34): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(355,61): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(356,60): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(357,65): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(357,97): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(358,60): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(359,58): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(360,59): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(361,58): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(362,61): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(362,117): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(363,42): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(365,81): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(366,78): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(367,76): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(368,73): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(431,6): error TS2304: Cannot find name 'Symbol'.
@types/core-js/index.d.ts(431,26): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(456,39): error TS2304: Cannot find name 'Promise'.
@types/core-js/index.d.ts(464,59): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(465,59): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(466,42): error TS2304: Cannot find name 'IterableIterator'.

@types/core-js/index.d.ts(467,48): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(468,69): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(472,40): error TS2304: Cannot find name 'PropertyKey'.

@types/core-js/index.d.ts(474,48): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(494,55): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(495,45): error TS2304: Cannot find name 'PropertyKey'.
@types/core-js/index.d.ts(535,42): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(536,39): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(537,41): error TS2304: Cannot find name 'IterableIterator'.
@types/core-js/index.d.ts(623,16): error TS2304: Cannot find name 'MapConstructor'.
@types/core-js/index.d.ts(624,16): error TS2304: Cannot find name 'SetConstructor'.
@types/core-js/index.d.ts(625,20): error TS2304: Cannot find name 'WeakMapConstructor'.
@types/core-js/index.d.ts(626,20): error TS2304: Cannot find name 'WeakSetConstructor'.
@types/core-js/index.d.ts(627,20): error TS2304: Cannot find name 'PromiseConstructor'.
@types/core-js/index.d.ts(646,53): error TS2304: Cannot find name 'Iterator'.
@types/core-js/index.d.ts(657,35): error TS2304: Cannot find name 'Promise'.
@types/core-js/index.d.ts(1280,36): error TS2339: Property 'for' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1284,43): error TS2339: Property 'hasInstance' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1288,50): error TS2339: Property 'isConcatSpreadable' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1292,40): error TS2339: Property 'iterator' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1296,38): error TS2339: Property 'keyFor' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1300,37): error TS2339: Property 'match' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1304,39): error TS2339: Property 'replace' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1308,38): error TS2339: Property 'search' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1312,39): error TS2339: Property 'species' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1316,37): error TS2339: Property 'split' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1320,43): error TS2339: Property 'toPrimitive' does not exist on type 'SymbolConstructor'.

@types/core-js/index.d.ts(1324,43): error TS2339: Property 'toStringTag' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(1328,43): error TS2339: Property 'unscopables' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2059,36): error TS2339: Property 'for' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2063,43): error TS2339: Property 'hasInstance' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2067,50): error TS2339: Property 'isConcatSpreadable' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2071,40): error TS2339: Property 'iterator' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2075,38): error TS2339: Property 'keyFor' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2079,37): error TS2339: Property 'match' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2083,39): error TS2339: Property 'replace' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2087,38): error TS2339: Property 'search' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2091,39): error TS2339: Property 'species' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2095,37): error TS2339: Property 'split' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2099,43): error TS2339: Property 'toPrimitive' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2103,43): error TS2339: Property 'toStringTag' does not exist on type 'SymbolConstructor'.
@types/core-js/index.d.ts(2107,43): error TS2339: Property 'unscopables' does not exist on type 'SymbolConstructor'.
nativescript-angular/platform-common.d.ts(32,67): error TS2304: Cannot find name 'Promise'.
nativescript-angular/platform-common.d.ts(33,101): error TS2304: Cannot find name 'Promise'.
nativescript-angular/platform-providers.d.ts(1,23): error TS2307: Cannot find module 'ui/frame'.
nativescript-angular/platform-providers.d.ts(2,22): error TS2307: Cannot find module 'ui/page'.
nativescript-angular/platform-providers.d.ts(4,24): error TS2307: Cannot find module 'platform'.
nativescript-angular/resource-loader.d.ts(4,23): error TS2304: Cannot find name 'Promise'.
nativescript-angular/router.d.ts(3,23): error TS2307: Cannot find module 'ui/frame'.
nativescript-angular/router/ns-location-strategy.d.ts(2,45): error TS2307: Cannot find module 'ui/frame'.
nativescript-angular/router/ns-module-factory-loader.d.ts(7,25): error TS2304: Cannot find name 'Promise'.

nativescript-angular/router/page-router-outlet.d.ts(3,24): error TS2307: Cannot find module 'platform'.
nativescript-angular/router/page-router-outlet.d.ts(4,23): error TS2307: Cannot find module 'ui/frame'.
nativescript-angular/router/router-extensions.d.ts(3,23): error TS2307: Cannot find module 'ui/frame'.
nativescript-angular/router/router-extensions.d.ts(10,67): error TS2304: Cannot find name 'Promise'.
nativescript-angular/router/router-extensions.d.ts(11,72): error TS2304: Cannot find name 'Promise'.
rxjs/Observable.d.ts(69,60): error TS2304: Cannot find name 'Promise'.

rxjs/Observable.d.ts(69,70): error TS2304: Cannot find name 'Promise'.

tns-core-modules/tns-core-modules.d.ts(14,18): error TS2304: Cannot find name 'Promise'.

tns-core-modules/tns-core-modules.d.ts(17,27): error TS2304: Cannot find name 'Headers'.
tns-core-modules/tns-core-modules.d.ts(19,44): error TS2304: Cannot find name 'RequestInit'.

tns-core-modules/tns-core-modules.d.ts(19,58): error TS2304: Cannot find name 'Promise'.

tns-core-modules/tns-core-modules.d.ts(110,18): error TS2300: Duplicate identifier 'log'.

TypeScript compiler failed with exit code 1

ネットで調べたところ、package.jsonもしくはtsconfig系のエラーであることが多いそうなので、
とりあえず前回は動いていたコードを持って来ることで解決しました

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "noEmitHelpers": true,
        "noEmitOnError": true,
        "lib": [
            "es6",
            "dom",
            "es2015.iterable"
        ],
        "baseUrl": ".",
        "paths": {
            "*": [
                "./node_modules/tns-core-modules/*",
                "./node_modules/*"
            ]
        }
    },
    "exclude": [
        "node_modules",
        "platforms",
        "**/*.aot.ts"
    ]
}



// package.json
{
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.tnschat",
    "tns-android": {
      "version": "3.0.1"
    }
  },
  "dependencies": {
    "@angular/animations": "~4.0.0",
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/forms": "~4.0.0",
    "@angular/http": "~4.0.0",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",
    "@angular/router": "~4.0.0",
    "email-validator": "^1.0.7",
    "nativescript-angular": "~3.0.0",
    "nativescript-social-share": "^1.3.2",
    "nativescript-theme-core": "~1.0.4",
    "reflect-metadata": "~0.1.8",
    "rxjs": "~5.2.0",
    "tns-core-modules": "~3.0.0",
    "zone.js": "0.8.2"
  },
  "devDependencies": {
    "babel-traverse": "6.24.1",
    "babel-types": "6.24.1",
    "babylon": "6.17.2",
    "lazy": "1.0.11",
    "nativescript-dev-android-snapshot": "^0.*.*",
    "nativescript-dev-typescript": "^0.4.0",
    "typescript": "~2.2.1"
  }
}

devise token auth を使って簡単に早くAPIを作る 2

※ちょくちょくGithubで公開してもらえませんか?的なことを聞かれるので、Bitbuckeのアカウントでコードを公開いたしました。ミスなどがあったらすみません。時間があるときに直します。
devise-token-auth 完成物のリンク

全て連続しているので上から順に進めていっていただけるとわかりやすいと思います!
devise token auth を使って簡単に早くAPIを作る1( api作成 )
devise token auth を使って簡単に早くAPIを作る2 ( jsonの出力 ) 今回はここ
devise token auth api をAngular4 でUIを実装する1 ( angularのセットアップ )
devise token auth api をAngular4 でUIを実装する2 ( ログインを繋げる )
devise token auth api をAngular4 でUIを実装する3 ( 新規登録 )
devise token auth api をAngular4 でUIを実装する4 ( ログインしやすくする)

以前devise token authを使ってAPIを作る記事を書いたのですが、
結構反応がよかったのでついでにAngularを使ってUIも作ってみようかと思います!

Angularを使って見るためにも、まずは簡単なデータを返すことができる様に追加していきます

scaffolding

以下のコードを実行します

$  rails g scaffold hobby name
$ rake db:migrate

今回はjsonを出力するためにjbuilderを使用するのでhobbies_controller.rbは以下の様に修正します

# ちなみにindexのみを扱う予定なので、showなどはご自身でお願いします
class HobbiesController < ApplicationController
  def index
    @hobbies = Hobby.all
    render 'index', :formats => [:json], :handlers => [:jbuilder]
  end
end

次はrails c でデータを作ります

Hobby.create(name: '野球')
Hobby.create(name: 'サッカー')
Hobby.create(name: 'テニス')

データを作成後下記リンクにアクセスすると

http://localhost:3000/hobbies

この様なjsonデータがレンダリングされています!

ここにdeviseと同じく制限をかけてみます

class HobbiesController < ApplicationController
  before_action :set_hobby, only: [:show, :update, :destroy]
  before_action :authenticate_api_user! # この行を追加!
  
  def index
    @hobbies = Hobby.all
    render 'index', :formats => [:json], :handlers => [:jbuilder]
  end
end

先ほどと同じ様にアクセスすると

ログインエラーが返ってきます

postmanを使って試して見る

ログインして返ってきた情報

  • access-token
  • client
  • uid

以下のリンクにGETリクエストをすることで

http://localhost:3000/hobbies

ログイン制限をかけることができます

rack corsの問題を回避

最後にですが、Angularに進む方はこの対策をしておいてください
rack corsを回避しないとリクエストが弾かれるという状況に陥ってしまうので、
今のうちに対処しときます

詳しい情報はネットにたくさん転がっていると思うので、一度調べておくと今後のためにもなると思います

module DeviseTokenAuth
  class Application < Rails::Application
    config.api_only = true

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*',
                 :headers => :any,
                 :expose => ['access-token', 'expiry', 'token-type', 'uid', 'client'],
                 :methods => [:get, :post, :options, :delete, :put]
      end
    end
  end
end

Angularではログイン機能全般を実装した上で、Hobbyを取得できるところまで進めていく予定です

次の記事
devise token auth api をAngular4 でUIを実装する1 ( angularのセットアップ )

django mysql初期設定

最近新しいフレームワークや言語を学んでいなかったので、djangoを初めてみました〜

はじめての Django アプリ作成、その 1
rails同様sqliteがデフォルトのようでしたが、mysqlに変更しました

mysqlへ変更するにはsettings.pyの

# デフォルト
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# 以下の様に変更
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mysite',
        'USER': 'root',
        'HOST': 'localhost'
    }
}

データベース関連の設定を決めたら次は

# 以下を実行
$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK

sequel pro で確認してみると
データベースができてます!
素敵!!!!!

railsはファイルが多すぎてちょっと嫌だな〜と思ってたので、
railsに比べてdjangoのファイルの数の少なさ、シンプルさに浮気しちゃいそうです

参考にした記事

How To Use MySQL or MariaDB with your Django Application on Ubuntu 14.04
Setting Django up to use MySQL