저는 모바일 Android 및 iOS 애플리케이션 개발의 열렬한 팬이며, 이러한 애플리케이션을 개발하는 데 Angular를 사용하는 것은 더더욱 열렬한 팬입니다. 얼마 전에 저는 네이티브스크립트 애플리케이션에서 카우치베이스 사용하기 뿐만 아니라 네이티브스크립트 앵귤러 애플리케이션에서 카우치베이스 사용하기. 둘 다 매우 간단한 할 일 목록 시나리오였습니다.
한 발 물러서서 한 번 자세히 살펴보겠습니다. 카우치베이스 가 모바일 애플리케이션에서 할 수 있는 일을 하나씩 소개합니다. 예를 들어, 카우치베이스는 키-값 또는 문서 속성으로 관리할 수 있는 문서 데이터베이스입니다. 이 예제에서는 키와 값을 사용하여 가상의 프로필 데이터를 저장하고 로드하는 작업을 해보겠습니다.

위의 예에서는 이름과 성을 추가하고 사용 가능한 프로필 아바타 목록에서 선택할 수 있습니다. 저장할 때 데이터가 Couchbase에 저장되고 화면이 초기화됩니다. 로드할 때는 이전에 저장한 키를 통해 데이터가 로드됩니다.
요구 사항
이 프로젝트가 작동하려면 몇 가지 기본 요구 사항이 있습니다:
- 네이티브 스크립트 CLI 2.0+
- Android SDK 및/또는 Xcode
프로젝트를 생성하고 빌드하려면 노드 패키지 관리자(NPM)를 통해 얻을 수 있는 네이티브스크립트 CLI가 필요합니다. 빌드 프로세스를 완료하려면 빌드하려는 플랫폼에 따라 Android SDK 또는 Xcode가 필요합니다.
Angular 프로젝트로 새 네이티브스크립트 시작하기
이해하기 쉽도록 Android 및 iOS용 NativeScript with Angular 프로젝트를 새로 만들어 보겠습니다. 명령줄에서 다음을 실행합니다:
|
1 2 3 4 |
tns create ProfileProject --ng cd ProfileProject tns platform add ios tns platform add android |
Xcode가 설치된 Mac을 사용하지 않는 경우 Android 플랫폼용으로만 빌드할 수 있습니다. iOS는 Mac 전용입니다.
이 프로젝트는 Couchbase를 사용할 것이므로 반드시 네이티브 스크립트 카우치베이스 플러그인을 설치합니다. CLI에서 실행합니다:
|
1 |
tns plugin add nativescript-couchbase |
위의 명령은 프로젝트에서 사용할 수 있는 모든 플랫폼에 대한 Couchbase 플러그인을 설치합니다. 이제 애플리케이션을 개발할 준비가 되었습니다.
핵심 애플리케이션 로직 정의하기
프로젝트에는 단일 페이지이지만 두 가지 핵심 애플리케이션 로직이 있습니다. 기본 페이지에 표시되는 로직과 모달 대화 상자에 표시되는 로직이 있습니다. 기본 페이지에 표시되는 로직부터 시작하겠습니다.
프로젝트의 app/app.component.ts 파일을 열고 다음을 포함하세요:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import { Component, ViewContainerRef } from "@angular/core"; import { ModalDialogService } from "nativescript-angular/directives/dialogs"; import { Couchbase } from "nativescript-couchbase"; import { ModalComponent } from "./app.modal"; @Component({ selector: "my-app", templateUrl: "app.component.html", }) export class AppComponent { public profile: any; private database: any; public constructor(private modal: ModalDialogService, private vcRef: ViewContainerRef) { } public showModal(fullscreen: boolean) { } public save() { } public load() { } } |
위 코드에서는 다양한 Angular 컴포넌트, NativeScript 모달 서비스, Couchbase 및 곧 생성될 모달 대화 상자를 가져오고 있습니다.
내 앱 컴포넌트 클래스에는 공용 변수와 개인 변수가 있습니다. 비공개 데이터베이스 변수는 오픈 카우치베이스 인스턴스와 공개 프로필 변수에는 사람 이름과 프로필 사진 등의 정보가 저장됩니다.
그리고 생성자 메서드는 모달다이얼로그 서비스 그리고 ViewContainerRef 페이지 전체에서 사용할 수 있는 서비스입니다.
|
1 2 3 4 5 6 7 8 |
public constructor(private modal: ModalDialogService, private vcRef: ViewContainerRef) { this.profile = { photo: "~/kitten1.jpg", firstname: "", lastname: "" } this.database = new Couchbase("data"); } |
또한 프로필 변수를 열고 데이터. 다음 사항을 확인할 수 있습니다. ~/kitten1.jpg 가 무엇인지 궁금해할 것입니다.
이 애플리케이션에서는 다음과 같은 몇 가지 아바타를 사용할 수 있습니다. kitten1.jpg, kitten2.jpg및 kitten3.jpg 프로젝트의 앱 디렉터리로 이동합니다.

이 사진들은 제가 직접 찍은 것이 아니라 인터넷에서 찾은 것입니다. 이 예제에는 원하는 이미지를 자유롭게 사용하세요.
그리고 profile.photo 속성에는 사용하려는 사진의 경로가 저장됩니다.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public save() { let document = this.database.getDocument("mydockey"); if(document) { this.database.updateDocument("mydockey", this.profile); } else { this.database.createDocument(this.profile, 'mydockey'); } this.profile = { photo: "~/kitten1.jpg", firstname: "", lastname: "" } } |
Couchbase에 저장하려면 먼저 문서가 Couchbase에 이미 존재하는지 확인해야 합니다. 이 애플리케이션은 단일 페이지 단일 프로필 애플리케이션이라는 점을 기억하세요. 문서가 존재하는 경우 문서에 있는 모든 내용을 프로필 변수로 설정하거나, 그렇지 않으면 생성합니다. 저장한 후에는 양식을 재설정할 수 있습니다.
|
1 2 3 |
public load() { this.profile = this.database.getDocument("mydockey"); } |
문서 키의 이름을 알고 있으므로 양식을 다시 로드할 때 문서를 검색할 수 있습니다. 저장된 데이터와 검색된 데이터는 모두 JSON 형식이므로 네이티브스크립트 애플리케이션에 유용합니다.
마지막으로 쇼모달 메서드를 사용합니다:
|
1 2 3 4 5 6 7 8 9 10 |
public showModal(fullscreen: boolean) { let options = { context: { promptMsg: "Pick your avatar!" }, fullscreen: fullscreen, viewContainerRef: this.vcRef }; this.modal.showModal(ModalComponent, options).then((res: string) => { this.profile.photo = res || "~/kitten1.jpg"; }); } |
위는 제가 찾은 내용을 변형한 것입니다. 네이티브스크립트 문서. 호출되면 곧 생성될 예정인 모달 컴포넌트 를 다양한 옵션과 함께 사용할 수 있습니다. 모달이 닫히면 반환된 값이 반환된 값이 profile.photo 반환되는 값은 이미지 경로여야 하기 때문입니다.
이제 모달 대화 상자를 만들려면 어떻게 해야 할까요?
이미지 선택을 위한 모달 대화 상자 만들기
모달을 만드는 것은 네이티브스크립트 페이지를 만드는 것과 거의 동일합니다. 하지만 페이지가 아닌 모달임을 증명하기 위해 다른 부트스트랩을 수행해야 합니다.
파일 만들기 앱/앱.모달.ts 를 열고 다음 코드를 포함하세요:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import { Component, Input } from "@angular/core"; import { ModalDialogParams } from "nativescript-angular/directives/dialogs"; @Component({ selector: "my-modal", template: ` <StackLayout margin="24" horizontalAlignment="center" verticalAlignment="center"> <Label [text]="prompt"></Label> <StackLayout orientation="horizontal" marginTop="12"> <Image src="~/kitten1.jpg" width="75" height="75" (tap)="close('~/kitten1.jpg')"></Image> <Image src="~/kitten2.jpg" width="75" height="75" (tap)="close('~/kitten2.jpg')"></Image> <Image src="~/kitten3.jpg" width="75" height="75" (tap)="close('~/kitten3.jpg')"></Image> </StackLayout> </StackLayout> `, }) export class ModalComponent { @Input() public prompt: string; constructor(private params: ModalDialogParams) { this.prompt = params.context.promptMsg; } public close(res: string) { this.params.closeCallback(res); } } |
제가 사용하고 있는 템플릿 대신 templateUl 여기. 게을러져서 다른 HTML 파일을 만들고 싶지 않았기 때문입니다. 템플릿에는 세 개의 이미지와 각 이미지에 대한 탭 이벤트가 있습니다. 탭하면 닫기 메서드가 호출되어 이전 페이지로 값을 전달합니다.
모달을 사용하려면 먼저 프로젝트의 앱/앱.모듈.ts file:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptModule } from "nativescript-angular/platform"; import { NativeScriptFormsModule } from "nativescript-angular/forms"; import { ModalDialogService } from "nativescript-angular/modal-dialog"; import { AppComponent } from "./app.component"; import { ModalComponent } from "./app.modal"; @NgModule({ declarations: [AppComponent, ModalComponent], entryComponents: [ModalComponent], bootstrap: [AppComponent], imports: [NativeScriptModule, NativeScriptFormsModule], providers: [ModalDialogService], schemas: [NO_ERRORS_SCHEMA] }) export class AppModule { } |
위에서는 모달다이얼로그 서비스 뿐만 아니라 모달 컴포넌트? 우리는 두 가지를 모두 @NgModule 블록.
이제 애플리케이션 내에서 모달을 실행할 수 있습니다.
핵심 애플리케이션 UI 개발
그렇다면 기본 네이티브스크립트 애플리케이션 페이지의 UI는 어떨까요? 프로젝트의 app/app.component.html 파일을 열고 다음 XML 마크업을 포함합니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<ActionBar title="{N} Profile"> <ActionItem text="Load" ios.position="right" (tap)="load()"></ActionItem> </ActionBar> <GridLayout rows="*, *" cols="*"> <Image [src]="profile.photo" (tap)="showModal(true)" width="150" height="150" class="img-rounded" row="0" col="0"></Image> <StackLayout class="form" row="1" col="0"> <StackLayout class="input-field"> <Label text="First Name" class="label"></Label> <TextField [(ngModel)]="profile.firstname" class="input input-border"></TextField> </StackLayout> <StackLayout class="input-field"> <Label text="Last Name" class="label"></Label> <TextField [(ngModel)]="profile.lastname" class="input input-border"></TextField> </StackLayout> <StackLayout class="input-field"> <Button text="Save" (tap)="save()" class="btn btn-primary w-full"></Button> </StackLayout> </StackLayout> </GridLayout> |
위의 레이아웃에는 작업 표시줄과 콘텐츠가 두 행으로 나뉘어 있습니다. 액션 바에는 버튼이 있으며, 버튼을 누르면 load 메서드를 사용합니다.
그리고 이미지 태그의 경로에 저장된 사진을 로드합니다. profile.photo 변수를 설정합니다. 탭하면 새 아바타를 선택할 수 있는 모달이 실행됩니다.
UI의 두 번째 행에는 두 개의 입력 필드와 버튼이 있습니다. 입력 필드는 Angular [(ngModel)] 태그를 추가하여 XML과 타입스크립트 간에 데이터를 공유할 수 있습니다. 버튼을 누르면 저장 메서드가 트리거되어 데이터를 Couchbase에 저장합니다.
결론
방금 사용 방법을 확인하셨습니다. 카우치베이스 를 키-값 저장소로 네이티브 스크립트 Angular로 빌드한 Android 및 iOS 애플리케이션. 다음 시간에는 단순한 키-값 저장소보다 훨씬 더 강력하게 Couchbase에 둘 이상의 문서를 저장하고 해당 문서를 쿼리하는 방법을 살펴보겠습니다.
[...] 그 동안 NativeScript 및 Angular를 통한 Couchbase Mobile의 키-값 연산이라는 제목의 다른 튜토리얼을 통해 Couchbase에서 NativeScript를 사용하는 방법에 대해 알아보세요. [...]