Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

久しぶりにAngularを使おうとしたらタイトルのエラーが出てきました

問題点は必要なモジュールをインポートしていなかったことで、解決方法はformmoduleをインポートしてやれば問題なく動きます

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

@NgModule({
    imports: [
         FormsModule      
    ]

久しぶりにプロジェクトを作ったのでとても初歩的なとこでつまづいてしまいました・・・

参考にした記事
Angular 4 – “Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’ ” error [duplicate]

Android-sdkエラー(Nativescript,Javaどっちでも)

※この記事はエラー内容を全て記述しています。したがって、エラーが出るべくして起こった箇所もあるため、一度全てに目を通してから読んだ方が時間のロスが少なくて済みます。私はNativescriptの開発中にエラーが出てきましたが、Android-sdkやパス、APIバージョンの問題なのでJavaやKotlinでも全く問題ないです。

 

Nativescriptを色々といじっていたらandroidが動かなくなってしまいました

通常通り起動すると、よくあるエラーが出てきています
エラーの内容はANDROID_HOMEというディレクトリはありません、ということですね
パスが間違っている、もしくはandroid-sdkがないのどちらかです

$ tns run android
The ANDROID_HOME environment variable is not set or it points to a non-existent directory. You will not be able to perform any build-related operations for Android.

ちなみにパスは以下のように設定してありますが、

export ANDROID_HOME=“/usr/local/share/android-sdk”
export PATH=“${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools”

android-sdkが怪しいので、念のためもう一回sdkをいれときます

$ brew cask reinstall android-sdk

ターミナルを再起動してもう一回実行したところ

$ tns run android
Cannot find a compatible Android SDK for compilation. To be able to build for Android, install Android SDK 22 or later.

新しいエラーが出てきたので、一歩進みました!

調べてみると、Androidのモジュールが足りていないっぽいのでAndroid studioから関連モジュールなどをインストール

まずは開く

Configureから SDK Managerを開く

右上のeditからパスを指定

パスを指定したらNextボタンを押してインストール実行

完了後再度実行してみたところ

$ tns run android
Cannot find a compatible Android SDK for compilation. To be able to build for Android, install Android SDK 22 or later.

エラー内容に変化が現れなかったので、sdkのバージョンを色々といれてみます
※先ほどインストールしたAPIは27だけでした

5分ほどでインストール完了!

再び実行してみると、

$ tns run android
Searching for devices...
Starting Android emulator with image Nexus_5_API_25
Cannot find connected devices.
Emulator start failed with: 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.
To list currently connected devices and verify that the specified identifier exists, run 'tns device'.
To list available emulator images, run 'tns device <Platform> --available-devices'.

 

動きました!!!!
私のパソコンは5,6年使っていて重いのでエミュレーターが動いていませんが、Nativescriptを動かすことはできました!

 

問題点

 

今回の問題点は2つあると思います
1つ目は、android-sdkがうまく接続されていなかったこと

homebrewでいれていたので、updateした時かいつかはわかりませんがパスがおかしくなっていた、バージョンが悪かった、そもそも削除してしまっていた、などの理由が考えられます

これらが原因でANDROID_HOMEが見つかりません!というエラーが出ていたのだと思います

2つ目は、APIのバージョンを「間違えていた」ことが問題でした。
現在使用しているパソコンではAPIバージョンが25のネクサスを使用しています

最初にいれたバージョンは27だったので、それが原因でした。。。

今回の記事は今後同じエラーが出てきたときに簡単に対処できるようにと思って書いた記事なので、長くて要点がわかりづらいと思い方も多いかと思いますが、順を追っていけば比較的解決に近くのではないかと思います

もし間違え等ございましたら、コメントください

参考にした記事

Having ANOTHER Error (follow up on #32139) when trying to brew cask install android-sdk on mac os x #32157

Set ANDROID_HOME environment variable in mac
NativeScript Advanced Setup: macOS

patrickhammond/android_instructions.md

Cannot find a compatible Android SDK for compilation when running `tns platform add android`

Cannot find a compatible Android SDK for compilation. To be able to build for Android, install Android SDK 22 or later #3825

Cannot find a compatible Android SDK for compilation when running `tns platform add android`

Nativescript 記事一覧をまとめました

Nativescriptはサーバーとの連結やSDK、バージョニングなど結構エラーに悩まされます
このブログの中でNativescript関連の記事をまとめてみました

[toc]

インストール関連

Nativescript インストール中にエラーが出るときの対処法
brew でAndroid-sdk 導入 + PATH指定 + emulatorの導入

アプリ申請関連

Nativescript アプリ申請の良記事を見つけたのでシェア
Nativescript ios 申請時にmarketing iconがないと言われた時の対処方法

package.jsonとか関連

Nativescript アプリ名の変更方法
Nativescript tsconfig関連のエラー

カメラ関連

Nativescirpt cameraモジュールの使い方

ルーティング関連

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

エミュレーター関連

Nativescript cannot run your app in native emulator

UI関連

Nativescriptでhmtlのspan的な要素を使いこなす
Nativescript radio ボタンの作り方
Nativescript Labelで長い文字列の表示

アプリが更新されない系

Nativescript iosだと更新されない時の対処方法

ストレージ関連

Nativescriptでlocal storage的な機能を使う

チュートリアルまとめ

Nativescript おすすめチュートリアル

その他

Nativescript Found peer TypeScript 2.2.2 Cannot find module ‘@angular/upgrade/static’.
Nativescriptプロジェクト開始後エラー

Nativescript インストール中にエラーが出るときの対処法

Nativescriptをインストールし直そうとしたら、以下のエラーが出てきました

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: abbrev@1.1.0 (node_modules/nativescript/node_modules/fsevents/node_modules/abbrev):
npm WARN enoent SKIPPING OPTIONAL DEPENDENCY: ENOENT: no such file or directory, rename '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/abbrev' -> '/usr/local/lib/node_modules/nativescript/node_modules/fsevents/node_modules/.abbrev.DELETE'

対処法はこちらのコードを実行することで解消できます

$ sudo rm -rf /usr/local/lib/node_modules/nativescript

$ npm install -g nativescript 

参考にした記事

What is causing this nativescript installation error on Macbook Pro

Nativescript アプリ申請の良記事を見つけたのでシェア

Nativescript製アプリを申請するときに役立った良記事です

Androidは結構簡単にできますが、iosは結構めんどくさいのですごく参考になります

参考にした記事

8 Steps to Publish Your NativeScript App to the App Stores

Nativescript アプリ名の変更方法

Nativescript package.jsonの中身を変更した後のエラー回避方法

Nativescriptのpackage.jsonは app/App_Rerources/Android/app.gradle に影響を与えます。
※Androidの場合

ですので、package.jsonの中身の変更をしたら

$ tns platform remove android 
$ tns run android

と実行することでエラーを回避することができます

以下は例です

// package.json

“nativescript”: {
  “id”: “com.testApplication.app”, // appの部分の名前を変更
  “tns-ios”: {
    “version”: “3.2.0"
  },
  “tns-android”: {
    “version”: “3.2.0”
  }




// app/App_Resources/Android/app.gradole 

android {
  defaultConfig {
    generatedDensities = []
    applicationId = “com.testApplication.app”
  }
  aaptOptions {
    additionalParameters “--no-version-vectors”
  }
}

参考にした記事

App not launching in device using command “tns run android” #2092

Nativescript ios 申請時にmarketing iconがないと言われた時の対処方法

タイトルの通り、NativescriptをiOS申請する時にちょこっとハマったので参考になった記事をシェアします

手順としては、

  • 1024 * 1024のファイルをpng形式で作成
  • App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/
    に作成したpngファイルを入れる
    ちなみにネーミングは”iTunesArtwork@2x.png”で登録しました

  • 同ディレクトリ内のContents.jsonにファイルの情報を記述
  • {
          "size": "1024x1024",
          "idiom": "ios-marketing",
          "filename": "iTunesArtwork@2x.png",
          "scale": "1x"
    }

とりあえずざっくりとしていますが、この流れで問題なくビルドすることができました!

参考にした記事

Missing Marketing Icon – iOS Apps must include a 1024x1024px Marketing Icon in PNG format
App Icons on iPhone, iPad and Apple Watch
Missing Marketing Icon
Where to find ‘Missing Marketing Icon’

Nativescriptでhmtlのspan的な要素を使いこなす

Nativescriptでhtmlのspan的な要素を使えるか調べてみたら見つかりました〜

とりあえず、サンプルコードはこちら
※アイキャッチ画像が実行後のイメージです


<Label class=“h3 p-15 m-15 text-left”>
    <FormattedString>
        <Span text=“Words ” color=“#006600”></Span>
        <Span text=“with ” color=“#990000” fontAttributes=“Bold”></Span>
        <Span text=“different ” color=“#ffcc00"></Span>
        <Span text=“color.“></Span>
    </FormattedString>
</Label>

ちなみにこちらのコードもサンプルで出ていましたけど、動きませんでした
コードはこちらの記事から見つけました

Bolding, Italicizing, and Underlining Portions of Text in NativeScript


<StackLayout class=“page m-20”>
  <Label>
    <FormattedString>
      <Span text=“NativeScript is an “></Span>
      <Span text=“AMAZING” fontAttributes=“Bold”></Span>
      <Span text=” framework.“></Span>
    </FormattedString>
  </Label>
</StackLayout>

参考にした記事

Bolding, Italicizing, and Underlining Portions of Text in NativeScript

Flask APIのページャ実装(超簡単!)

Flaskで簡単にAPIのページャ機能を作りました〜

とりあえずコードはこんな感じ

from flask import Flask
from flask.json import jsonify
from flask.globals import request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/pager'

db = SQLAlchemy(app)

"""
    データベースの作成手順は、
    1.まず python コンソールで
    from app import db でインポートして
    2.one-to-manyのデータベースを作成する(直接mySqlで作るか、seqel proなどを使用すると楽です )
    3.作成し終わったら、再びpython コンソールで
    db.create_all() を叩いて完成!
"""


class Data(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name
        }


@app.route('/')
def index():
    """
    offset は刻み offset=5であれば5刻みでリクエストを処理
    一度にリクエストすると、サーバーに負荷がかかり過ぎてしまうので、
    1度目のリクエストは offset=0
    2度目のリクエストは offset=5
    3度目のリクエストは offset=10
    のようにリクエストしていけば、APIのページャとして機能する

    limitは文字通り上限を設けること
    """
    # request のクエリパラムスからoffset部分を取得する
    offset = request.args.get('offset', type=int)
    # request のクエリパラムスからlimit部分を取得する
    limit = request.args.get('limit', type=int)

    response = [Data.to_dict(n) for n in Data.query.offset(offset).limit(limit)]
    return jsonify({'response': response})


if __name__ == '__main__':
    app.run()

 

 

コメントとして結構書いてあるので、こんな感じで使えますよーという例をいくつか提示します

何もしない場合

url -> http://localhost:5000/

# 帰ってくるデータ
{
    "response": [
        {
            "id": 1,
            "name": "太郎"
        },
        {
            "id": 2,
            "name": "一郎"
        },
        {
            "id": 3,
            "name": "二郎"
        },
        {
            "id": 4,
            "name": "三郎"
        },
        {
            "id": 5,
            "name": "金太郎"
        },
        {
            "id": 6,
            "name": "武蔵"
        },
        {
            "id": 7,
            "name": "john"
        },
        {
            "id": 8,
            "name": "david"
        },
        {
            "id": 9,
            "name": "matt"
        },
        {
            "id": 10,
            "name": "joy"
        }
    ]
}


 

 

offsetとlimitをつける場合

url -> http://localhost:5000/?offset=0&limit=5

{
    "response": [
        {
            "id": 1,
            "name": "太郎"
        },
        {
            "id": 2,
            "name": "一郎"
        },
        {
            "id": 3,
            "name": "二郎"
        },
        {
            "id": 4,
            "name": "三郎"
        },
        {
            "id": 5,
            "name": "金太郎"
        }
    ]
}


# 次の5件をリクエストするには
 url - > url -> http://localhost:5000/?offset=5&limit=5

{
    "response": [
        {
            "id": 6,
            "name": "武蔵"
        },
        {
            "id": 7,
            "name": "john"
        },
        {
            "id": 8,
            "name": "david"
        },
        {
            "id": 9,
            "name": "matt"
        },
        {
            "id": 10,
            "name": "joy"
        }
    ]
}

 

offsetとlimitだけでもリクエスト処理やユーザビリティが改善します
簡単なので、是非使うことも検討してみてください!

 

 

Angular4 SEO対策(titleとdescriptionの設定)

Angularでtitleとdescriptionをページごとに設定してみようかなと思って調べてみたら、簡単な方法は見つかりましたのでシェアしたいと思います

とりあえず、まずはプロジェクトを作ります

$ ng new seo-sample

# 終わったら
$ ng serve

完了したら、localhost:4200 にアクセスします

うおーすげえ!
最近プロジェクトを作っていなかったので知らなかったんですけど、こんな画面になってます!!!

話が脱線してしまいましたが、本題に戻ります

デフォルトだと、titleは

<title>SeoSample</title>

になっていて、descriptionはありません
こんな感じになっています

このtitleとdescriptionを管理するには以下のように app.component.tsを修正します

import {Component, OnInit} from '@angular/core';
// metaタグの設定とかできるようにするため +  titleを入れたり修正したり
import {Meta, Title} from '@angular/platform-browser';


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

  constructor(private meta: Meta,
              private title: Title) {
  }

  ngOnInit() {
    this.setDescription('せんべいうまい。特に黒豆のやつやばい。のりも捨て難い');
    this.setTitle('SeoSampleについて  | せんべいって美味しいよね');
  }


  setDescription(description: string) {
    // ブログなどのデータを入れる場合はなんどもdescriptionが追加されてしまうため、
    // descriptionを入れる前に既存のdescriptinoを削除しておく
    this.meta.removeTag("name='description'");
    this.meta.addTag({name: 'description', content: description});
  }

  setTitle(title: string) {
    this.title.setTitle(title);
  }

}

すると以下のようにtitleとdescriptionが変更されてるのがわかるかと思います

とりあえずは、これで簡単にSEO対策はできます

簡単なホームページの場合であれば、そこまで考えることは必要無いかもしれませんが、
ルーティングが複雑になる状況や、個別にdescriptinやtitleを設定することで集客力などを向上させて行く際は必ずやるべきことだと思います

ただ、難しいことはしていないのでやるべきこととしては、seo.service.tsを作ってできる限り綺麗にまとめとくことぐらいですかね
どのページにも入れなきゃいけないと思うんで

参考にした記事

Meta
Angular2 – SEO – how to manipulate the meta description
Angular 4.0 Platform Server Ability to Set Title and Meta Tags #15742